2011-05-26 46 views
8

方案:具有隻讀文本框和按鈕的UserControl。只要按下按鈕,TextBox.Text就會被修改和更新。WPF:更新不帶INotifyPropertyChanged(UserControl)的依賴屬性

問題: TextControl.Text屬性綁定到UserControl.Message依賴項屬性,但不會在UserControl.Message從UserControl內修改時更新。但是,實現INotifyPropertyChanged時,目標會更新。

我實際上並不需要在依賴屬性上實現INotifyPropertyChanged嗎?我錯過了什麼?請參閱演示代碼here

謝謝。

消息財產申報

public static readonly DependencyProperty MessageProperty = 
     DependencyProperty.Register("Message", typeof (string), 
     typeof (TextControl), new FrameworkPropertyMetadata("[WPFApp]" + 
     Environment.NewLine, OnMessageChanged, OnMessageCoerce)); 

    public string Message 
    { 
     get { return (string) GetValue(MessageProperty); } 
     set { SetValue(MessageProperty, value); } 
    } 

    private static object OnMessageCoerce(DependencyObject obj, 
     object baseValue) 
    { 
     return (string) obj.GetValue(MessageProperty) + (string) baseValue; 
    } 

    private static void OnMessageChanged(DependencyObject d, 
     DependencyPropertyChangedEventArgs e) 
    { 
     // do i need to do this? 
     ((TextControl) d).NotifyPropertyChanged("Message"); 
    } 

用戶控件簡稱XAML

<UserControl x:Class="WPFApp.TextControl" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" d:DesignHeight="64" d:DesignWidth="355" 
     DataContext="{Binding RelativeSource={RelativeSource Self}}"> 
<Grid> 
    <TextBox Text="{Binding Message, Mode=OneWay}" ... /> 
    <Button ... /> 
</Grid> 
</UserControl> 

回答

6

1)不,你不必叫NotifyPropertyChanged爲DependencyProperties。
2)使用的結合相對來源:

<TextBox Text="{Binding Message, Mode=OneWay,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" ... /> 

其他信息:

要找到結合相關的錯誤,看看在Visual Studio outut窗口綁定錯誤消息。他們大多非常清楚,並很快引導您解決問題。

+0

完美的解決方案!我會盡量多關注輸出窗口,但在這種情況下它似乎不會顯示綁定錯誤。再次感謝。 – BakaBoy 2011-05-26 21:22:03

+1

爲什麼需要RelativeSource?爲什麼DataContext不是繼承的? – 2015-01-10 04:13:34