将控件属性绑定到Window ViewModel的类的属性
本文关键字:属性 ViewModel Window 控件 绑定 | 更新日期: 2023-09-27 18:26:31
我想将TextBox的Text属性绑定到ViewModel的属性的子级。
这是我的代码:
foo.cs:
public class foo()
{
public foo()
{
Bar = "Hello World";
}
public string Bar { Get; private Set;}
//Some functions
}
ViewModel.cs:
public class ViewModel : INotifyPropertyChanged
{
public foo Property { Get; Set; }
//some more properties
public ViewModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Window.xaml.cs:
public ViewModel MyViewModel { get; set; }
public Window()
{
MyViewModel = new ViewModel();
this.DataContext = MyViewModel;
MyViewModel.Property = new foo();
}
Window.xaml:
<!--
Some controls
-->
<TextBox Text="{Binding Path=Property.Bar}"></TextBox>
我也试过这和这个,但没有一个对我有效。
您已经在ViewModel
上实现了INotifyPropertyChanged
,但当Property
更改为时,您从未调用过它
尝试:
public class ViewModel : INotifyPropertyChanged
{
private foo _property;
public foo Property
{
get{ return _property; }
set{ _property = value; OnPropertyChanged(); }
}
.................