好吧,我认为这将是一个明智的选择,但显然我做错了什么。问题是,当单击Extended WPF工具包DoubleUpDown控件的“向上”和“向下”按钮时,值不会正确更新。单击“向上”时,控件中的值会更改,但视图模型不会更新。只有当我从单击向上更改为单击向下时,模型才会更新,但使用之前的值。
为了重现,我使用了一个简单的视图模型:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
MyValue = 0.5;
}
private double _myValue;
public double MyValue
{
get { return _myValue; }
set
{
_myValue = value;
PropertyChanged(this, new PropertyChangedEventArgs("MyValue"));
}
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
我的MainWindow.xaml看起来像下面的代码,其中DoubleUpDown控件和标签都以TwoWay方式绑定到ViewModel的MyValue属性:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
Title="MainWindow" Height="100" Width="200">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<xctk:DoubleUpDown
Value="{Binding MyValue, Mode=TwoWay}"
Increment="0.5"
Minimum="0.0"
Maximum="10"
ValueChanged="DoubleUpDown_ValueChanged"
/>
<Label Grid.Column="1" Content="{Binding MyValue, Mode=TwoWay}"/>
</Grid>
</Window>
在代码隐藏中,我将MainWindow构造函数中的DataContext设置为ViewModel的实例:
public MainWindow()
{
DataContext = new ViewModel();
InitializeComponent();
}
答案 0 :(得分:1)
DoubleUpDown控件的默认绑定更新逻辑是LostFocus
。尝试在您的绑定中明确设置UpdateSourceTrigger=PropertyChanged
,如下所示 -
<xctk:DoubleUpDown
Value="{Binding MyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Increment="0.5"
Minimum="0.0"
Maximum="10"
ValueChanged="DoubleUpDown_ValueChanged"/>