注意:我使用的是PostSharps NotifyPropertyChanged属性。
当我在ctor中设置属性时,我在视图中看到文本框更新,但是如果我将单击事件连接到按钮并将相同的属性设置为其他文本框未更新的属性。我做错了什么?
public partial class TestForm : Window
{
private MyViewModel _vm;
public TestForm()
{
InitializeComponent();
_vm = new MyViewModel();
DataContext = _vm;
_vm.MyText = "Test 1"; //Updates in UI
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_vm.MyText = "Test 2"; //No update in UI
}
}
[NotifyPropertyChanged]
public class MyViewModel
{
public string MyText { get; set; }
}
查看
<Window x:Class="MyApp.Forms.Activate.TestForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="300" Height="300">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23"
TextWrapping="Wrap" Text="{Binding Path=MyText}"
Margin="0,123" Width="100" />
<Button Content="Button" Margin="29,154,0,0"
VerticalAlignment="Top" Width="75"
Click="Button_Click"/>
</Grid>
答案 0 :(得分:0)
您需要在模型上实现INotifyPropertyChanged
public class MyViewModel : INotifyPropertyChanged
{
private string _myText
public string MyText { get {return _myText;} set { if (value != _myText) _myText = value; RaisePropertyChanged(); } }
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
我没有通过编译器抛出它,但它看起来正确; - )
答案 1 :(得分:0)
我不认为NotifyPropertyChanged
属性有效。反正我也没见过它。
尝试更像这样的事情:
public class MyViewModel : INotifyPropertyChanged
{
private string _myText;
public string MyText
{
get
{
return _myText;
}
set
{
if (_myText != value)
{
_myText = value;
OnPropertyChanged("MyText");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
答案 2 :(得分:0)
提供绑定到PropertyChanged的文本框的UpdateSourceTrigger。
答案 3 :(得分:0)
事实证明代码没有任何问题。重新安装PostSharp后,它开始工作。