gpt4 book ai didi

c# - 将控件属性绑定(bind)到 Window ViewModel 类的属性

转载 作者:行者123 更新时间:2023-11-30 15:32:59 25 4
gpt4 key购买 nike

我想将 TextBox 的 Text 属性绑定(bind)到 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();
}

窗口.xaml:

    <!--
Some controls
-->

<TextBox Text="{Binding Path=Property.Bar}"></TextBox>

我也试过 thisthis ,但它们都不适合我。

最佳答案

您已经在您的 ViewModel 上实现了 INotifyPropertyChanged,但您从未在 Property 更改时调用它

尝试:

public class ViewModel : INotifyPropertyChanged
{
private foo _property;
public foo Property
{
get{ return _property; }
set{ _property = value; OnPropertyChanged(); }
}

.................

关于c# - 将控件属性绑定(bind)到 Window ViewModel 类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18077420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com