WPF: обновить свойство зависимости без INotifyPropertyChanged (UserControl) - PullRequest
8 голосов
/ 27 мая 2011

Сценарий: UserControl, который имеет TextBox только для чтения и кнопку. TextBox.Text изменяется и обновляется при каждом нажатии кнопки.

Проблема: Свойство TextControl.Text связано со свойством зависимостей UserControl.Message, но не обновляется, когда UserControl.Message изменяется изнутри UserControl. Тем не менее, target обновляется при реализации INotifyPropertyChanged.

На самом деле мне не нужно реализовывать INotifyPropertyChanged для свойства зависимостей? Что мне не хватает? Пожалуйста, смотрите демонстрационный код здесь .

Спасибо.

Сообщение об объявлении свойства

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

UserControl сокращенно 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>

1 Ответ

6 голосов
/ 27 мая 2011

1) Нет, вам не нужно вызывать NotifyPropertyChanged для DependencyProperties.
2) Используйте относительный источник для привязки:

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

Дополнительная информация:

Чтобы найти связанные с привязкой ошибки, посмотрите в выходном окне Visual Studio сообщения об ошибках привязки. Они в основном очень четкие и быстро приводят вас к проблеме.

...