请考虑以下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
中输入值时,该值不会更新为目标。
高度是依赖属性。由于其价值可能在多个地方“设定”,因此有一个precendence list。
直接设置其值(本地值)具有绑定优先级。在我提供的链接中明确说明:
对本地值的任何更改都将完全替换动态资源或绑定
你的bttn_Click
事件会更新你的Button
身高,但它不会像你想要的那样更新到Textbox
中输入的高度,正如你的绑定所暗示的那样。
为了保存这两个动作,我建议将你的Button
Height属性绑定到Text
的Textbox
值,就像你已经完成的那样,但是使用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}"
注意:高度仅在验证文本时更新,具体取决于您的配置方式。
以编程方式设置Height
属性可以有效地清除您在XAML标记中定义的绑定。
您应该通过设置绑定的source属性来更改高度,即Text
的TextBox
属性:
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();
}
另一种选择是将Mode
的Binding
设置为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
绑定。