[WP7][MVVM Light 工具包] 使用 mvvm-light 工具包时在绑定之前过早引发按钮命令
-
26-09-2019 - |
题
我在 Windows Phone 7 应用程序中使用 mvvm-light 工具包。
我认为:
<TextBox Height="78" HorizontalAlignment="Left" Margin="108,33,0,0" VerticalAlignment="Top" Width="313" Text="{Binding MyValue, Mode=TwoWay}" />
<Button Content="Go" Height="78" HorizontalAlignment="Left" Margin="127,252,0,0" Name="button1" VerticalAlignment="Top" Width="213" cmd:ButtonBaseExtensions.Command="{Binding DoCommand}" />
我的视图模型是:
public class MainPageViewModel : ViewModelBase
{
public ICommand DoCommand { get; internal set; }
public MainPageViewModel()
{
DoCommand = new RelayCommand(() =>
{
DoSomethingWith(MyValue);
}, () => true);
}
private const string MyValuePropertyName = "MyValue";
private string _myValue;
public string MyValue
{
get { return _myValue; }
set
{
if (_myValue == value)
return;
_myValue = value;
RaisePropertyChanged(MyValuePropertyName);
}
}
}
在模拟器中,当我在文本框中键入值时,然后单击按钮时,我可以看到我首先要在RelayCommand lambda表达式中进行,并且有一个断点,我看到myValue是无效的。然后,到达 MyValue setter 中的断点,并且正确的值进入 MyValue。
我究竟做错了什么 ?当然,我希望 setter 可以在 RelayCommand 之前到达......
预先感谢您的任何帮助。
解决方案
您可能遇到了 TextChanged 事件的 TextBox DataBinding 问题。这是 Silverlight 3 中公认的问题, 请参阅讨论此问题的线程 以及解决方法。一个巧妙的解决方案可能是使用中讨论的行为 本文.
HTH,indyfromoz
不隶属于 StackOverflow