按钮单击后绑定中断

问题描述 投票:0回答:3

请考虑以下xaml代码。

<TextBox x:Name="txtbox1" Grid.Row="1" Background="Aqua" Height="33" Width="55" Text="45"/>
<Button Content="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Height}"
        Click="bttn_Click"   x:Name="bttn" 
        Height="{Binding ElementName=txtbox1, Path=Text, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
        Grid.Row="2" />

bttn_Click如下,

private void bttn_Click(object sender, RoutedEventArgs e)
{
    double randomNo = 10;
    Random random = new Random();
    randomNo = random.Next(45,85);
    this.bttn.Height = randomNo;
}

点击Button后,目标值更新了。但在此之后,当我在TextBox中输入值时,该值不会更新为目标。

wpf xaml
3个回答
2
投票

高度是依赖属性。由于其价值可能在多个地方“设定”,因此有一个precendence list

直接设置其值(本地值)具有绑定优先级。在我提供的链接中明确说明:

对本地值的任何更改都将完全替换动态资源或绑定


0
投票

你的bttn_Click事件会更新你的Button身高,但它不会像你想要的那样更新到Textbox中输入的高度,正如你的绑定所暗示的那样。

为了保存这两个动作,我建议将你的Button Height属性绑定到TextTextbox值,就像你已经完成的那样,但是使用Converter将字符串解析为int / double。

变流器

public object Convert(object value, Type targetType, object parameter,
        CultureInfo culture)
    {
        var text = (string)value;

        return Int32.Parse(text);
    }

然后你的Button高度:

Height="{Binding ElementName=txtbox1, Path=Text,
Converter={StaticResource TextToIntConverter},
UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"

注意:高度仅在验证文本时更新,具体取决于您的配置方式。


0
投票

以编程方式设置Height属性可以有效地清除您在XAML标记中定义的绑定。

您应该通过设置绑定的source属性来更改高度,即TextTextBox属性:

private void bttn_Click(object sender, RoutedEventArgs e)
{
    double randomNo = 10;
    Random random = new Random();
    randomNo = random.Next(45, 85);
    this.txtbox1.Text = randomNo.ToString();
}

另一种选择是将ModeBinding设置为TwoWay

<Button Content="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Height}"
        Click="bttn_Click"   x:Name="bttn" 
        Height="{Binding ElementName=txtbox1, Path=Text, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
        Grid.Row="2" />

这是因为当您以编程方式设置属性时,不会清除TwoWay绑定,unline OneWay绑定。

© www.soinside.com 2019 - 2024. All rights reserved.