WPF数据与内部元素绑定

时间:2014-08-07 04:51:16

标签: c# wpf data-binding

我想将StackPanel组件绑定到一个对象,将其属性绑定到StackPanel

元素
<StackPanel Grid.Column="0" Grid.Row="0" Name="device1" Background="#CC119EDA" DataContext="{Binding}">
    <Label FontSize="22" Foreground="White">Desk #1</Label>                   
    <TextBox Text="{Binding Name}" />
</StackPanel>

在代码背后

device1.DataContext = new Class { Name = "Name" };

这种绑定有什么问题?感谢

1 个答案:

答案 0 :(得分:0)

你可以这样试试。当您将属性设置为Object时,UI线程不知道更改,因此您需要实现RaisePropertyChange机制。使用MvvmLight Toolkit是一个很大的优势。这里将窗口datacontext设置为可以继承所有元素。

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private string _name;

    public string MyName
    {
        get { return _name; }
        set
        {
            _name = value;
            OnPropertyChanged("MyName");
        }
    }


    public MainWindow()
    {
        InitializeComponent();
        MyName = "Eldho";
        this.DataContext = this;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

的Xaml

 <StackPanel>
        <Label>Hi,</Label>
        <TextBox Text="{Binding MyName}"/>
 </StackPanel>