开发者

Silverlight Binding Textbox Text property to public property of UserControl Problem

I have a user control which implements INotifyPropertyChanged and has a property SelectedTopicDescription and I am trying to bind a textbox Text property to this public property. I know the property is changing however the textbox is not being updated.

I have tried a number of things and I know this should be easy.

I have tried using the following datacontext within the UserControl xaml but it had no effect. I have read about dependency properities but shouldn't i be able to do this by using INotifyPropertyChanged?

Your help is appreciated.

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));
    }

...

The textbox is.. Width="200" Margin="141,142,0,153" Text="{Binding SelectedTopicDescription}" HorizontalAlignment="Left">


It's probably not a good idea to fiddle around with DataContext when binding elements in a Usercontrol with properties of the that UserControl. Instead direct the binding to the UserControl via the ElementName property of Binding, like this:-

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

This uses the fact that the Content element in the user control is has the name "LayoutRoot" and that in turn being a FrameworkElement has a Parent property which will be the UserControl.


Mode=TwoWay, at the DataBinding XAML expression

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜