1

I am using wpf. I want to bind a textbox with a simple string type value initialized in xaml.cs class. The TextBox isn't showing anything. Here is my XAML code:

<TextBox Grid.Column="1" Width="387" HorizontalAlignment="Left" Grid.ColumnSpan="2" Text="{Binding Path=Name2}"/>

And the C# code is this:

public partial class EntitiesView : UserControl
{
    private string _name2;
    public string Name2
    {
        get { return _name2; }
        set { _name2 = "abcdef"; }
    }
    public EntitiesView()
    {
        InitializeComponent();
    }
}
4

3 回答 3

8

你永远不会设定你的财产的价值。在您实际执行设置操作之前,简单地定义set { _name2 = "abcdef"; }并不会实际设置您的属性的值。

您可以将代码更改为如下所示以使其正常工作:

public partial class EntitiesView : UserControl
{
    private string _name2;
    public string Name2
    {
        get { return _name2; }
        set { _name2 = value; }
    }

    public EntitiesView()
    {
        Name2 = "abcdef";
        DataContext = this;
        InitializeComponent();
    }
}

此外,正如人们所提到的,如果您打算稍后修改属性的值并希望 UI 反映它,则需要实现INotifyPropertyChanged接口:

public partial class EntitiesView : UserControl, INotifyPropertyChanged
{
    private string _name2;
    public string Name2
    {
        get { return _name2; }
        set
        {
            _name2 = value;
            RaisePropertyChanged("Name2");
        }
    }

    public EntitiesView()
    {
        Name2 = "abcdef";
        DataContext = this;
        InitializeComponent();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
于 2013-07-20T17:02:42.157 回答
2

EntitiesView只需在构造函数中添加这一行

DataContext = this;
于 2013-07-20T21:30:49.013 回答
0

为什么不添加视图模型并将您的财产保留在那里?

查看模型类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace WpfApplication1
{
    public class TestViewModel : INotifyPropertyChanged
    {
        public string _name2;
        public string Name2
        {
            get { return "_name2"; }
            set
            { 
                _name2 = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Name2"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, e);
            }
        }
    }
}

EntityView 用户控制

public partial class EntitiesView : UserControl
{

    public EntitiesView()
    {
        InitializeComponent();
        this.DataContext = new TestViewModel();
    }
}
于 2013-07-20T17:03:01.253 回答