这是重现此问题的代码:
xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Text="{Binding Num, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBox>
</Grid>
C#:
using System.ComponentModel;
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Entity();
}
}
public class Entity : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double num;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public double Num
{
get { return num; }
set
{
num = value;
if (value > 100)
{
num = 100;
}
OnPropertyChanged("Num");
}
}
}
}
现在,如果我运行它,输入1,就可以了。然后再输入1,就变成11了,还是可以的。
然后再输入一个 1,即 111,现在验证将起作用并将值更改为 100,UI 将显示 100。
但是如果我输入更多数字,UI 不会改变,它会是 1001。
我想这与两次将属性设置为相同的值(100)有关。
但我不知道如何修复它,通过修复它,我的意思是让 UI 始终遵循属性值。
Thanks
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<!--The Too tip for the textbox-->
<Style x:Key="txterror" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"></Setter>
<Setter Property="Background" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox x:Name="txt" Text="{Binding Mode=TwoWay, IsAsync=True, Path=Num, UpdateSourceTrigger=PropertyChanged}" Margin="63,36,71,184" >
<TextBox.Effect>
<DropShadowEffect ShadowDepth="5"/>
</TextBox.Effect>
</TextBox>
<TextBox Margin="63,96,71,124" Text="{Binding ElementName=txt,Path=Text}">
<TextBox.Effect>
<DropShadowEffect ShadowDepth="5" />
</TextBox.Effect>
</TextBox>
</Grid>
</Window>
使用上面的代码其工作逻辑良好。
意味着当您设置 Num proeprty 的值时,它将属性值设置为 100,但窗口的文本框值不会更改。
这是因为它使用错误验证的框架元素,所以无论您想要放入文本框中的内容,它都会键入该内容并将该值显示在文本框中。但当属性值高于 100 时,属性值始终为 100。
您的解决方案是使用异步=真在您具有约束力的声明中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)