依赖项 属性 未更新视图

Dependency property is not updating the view

我有一个绑定到 ObservableCollection“MenuButtons”的 ItemsControl。 在 ItemsControl 中,我想通过依赖属性以编程方式添加一些按钮。

我的问题是我传递的值没有更新。默认值显示在视图中。

C#

  private void btnTest_Click(object sender, RoutedEventArgs e)
    {
        var vm = DataContext as UflMainWindowViewModel;
        vm.MenuButtons.Add(new UflMenuButton { IconText="Test123", Style = (Style)Application.Current.Resources["UflMenuButtonStyle"] });
    }

C# UflButtonClass

public class UflMenuButton : Button
{
    public string IconText
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("IconText", typeof(string), typeof(UflMenuButton), new UIPropertyMetadata("default", new PropertyChangedCallback(IconTextChanged)));

    private static void IconTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        UflMenuButton button = (UflMenuButton)sender;
        button.IconText = (string)e.NewValue;
    }
}

具有以下样式:

WPF

<Style x:Key="UflMenuButtonStyle" TargetType="{x:Type local:UflMenuButton}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Path=(local:UflMenuButton.IconText),RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Center"/>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

您可以绑定到 UflMenuButton 类型的第一个祖先:

<TextBlock Text="{Binding IconText, RelativeSource={RelativeSource AncestorType={x:Type local:UflMenuButton}}}" HorizontalAlignment="Center"/>

这项工作,但我认为存在更优雅的方式。