【问题标题】:Silverlight Binding Textbox Text property to public property of UserControl ProblemSilverlight 将文本框文本属性绑定到 UserControl 问题的公共属性
【发布时间】:2011-05-17 00:03:44
【问题描述】:

我有一个用户控件,它实现了 INotifyPropertyChanged 并有一个属性 SelectedTopicDescription,我正在尝试将一个文本框 Text 属性绑定到这个公共属性。我知道属性正在改变,但文本框没有更新。

我尝试了很多方法,我知道这应该很容易。

我尝试在 UserControl xaml 中使用以下数据上下文,但没有效果。我已经阅读了有关依赖属性的信息,但我不应该通过使用 INotifyPropertyChanged 来做到这一点吗?

感谢您的帮助。

DataContext="{Binding RelativeSource={RelativeSource Self}}"

public partial class CodePage : UserControl  ,INotifyPropertyChanged{

    private string _selectedTopicDescription = string.Empty;
    public string SelectedTopicDescription {
        get { return _selectedTopicDescription; }
        set { 
            _selectedTopicDescription = value; 
            OnPropertyChanged("SelectedTopicDescription"); 
        }
    }

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

...

文本框是.. 宽度="200" 边距="141,142,0,153" Text="{绑定 SelectedTopicDescription}" Horizo​​ntalAlignment="左">

【问题讨论】:

  • 你试过直接在代码中赋值DataContext吗?

标签: silverlight


【解决方案1】:

在将用户控件中的元素与该用户控件的属性绑定时,摆弄DataContext 可能不是一个好主意。而是通过BindingElementName 属性将绑定定向到UserControl,如下所示:-

<TextBox Text="{Binding Parent.SelectedTopicDescription, ElementName=LayoutRoot, Mode=TwoWay}" />

这使用了这样一个事实,即用户控件中的 Content 元素具有名称“LayoutRoot”,而 FrameworkElement 又具有 Parent 属性,即 UserControl

【讨论】:

    【解决方案2】:

    Mode=TwoWay,在 DataBinding XAML 表达式中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-12
      • 2011-01-13
      • 2010-11-11
      • 2011-07-29
      • 1970-01-01
      • 2023-04-06
      • 2012-07-11
      • 1970-01-01
      相关资源
      最近更新 更多