繁体   English   中英

将 XAML 属性绑定到 wpf 核心中我的 DataContext(ViewModel)之外的自定义对象属性

[英]Binding XAML properties to custom Object properties outside my DataContext (ViewModel) in wpf core

我试图将 XAML 中的某些属性绑定到我创建的自定义类的某些实例化对象的属性,但没有成功。 到目前为止我所拥有的是(简化):

在 MainWindow.xaml 中:

<TextBox 
    Text="{Binding TEXTBOX.Text}"
    ...
<TextBox/>

在 MainWindow.xaml.cs 中:

public MainWindow()
{
    var viewModel = new ViewModel();
    DataContext = viewModel;
    InitializeComponent();
}

在 ViewModel.cs 中:

public ViewModel()
{
    GuiObject TEXTBOX = new GuiObject();
    TEXTBOX.Text = "starting text";
}

在我的 GuiObject.cs 中:

public class GuiObject : INotifyPropertyChanged
{
    private string _text = String.Empty;
    public string Text
    {
        get => _text;
        set => SetProperty(ref _text, value);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public bool SetProperty<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
    {

        if (!EqualityComparer<T>.Default.Equals(field, newValue))
        {
            field = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            return true;
        }
        return false;
    }
}

有人可以指出我如何解决这个问题吗? 提前致谢!

public ViewModel()
{
    GuiObject TEXTBOX = new GuiObject();
    TEXTBOX.Text = "starting text";
}

这里的TEXTBOX是一个局部变量。 它不能从外部方法访问。 绑定需要公共属性才能工作:

public ViewModel()
{
    TEXTBOX = new GuiObject { Text = "starting text" };
}

public GuiObject TEXTBOX { get; set; }

另外:属性的命名指南是PascalCase ( public GuiObject TextBox { get; set; } )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM