如何在 C# WPF 中将属性从 CustomControl 传递到它的 UserControls?

How do I pass Properties from a CustomControl to it's UserControls in C# WPF?

目前我的代码中有一些 DependencyProperties 有问题。我制作了自己的 Control,它应该在我的应用程序的许多实例中使用。我能够绑定一个布尔值 DependencyProperty 并在控件本身中使用它的值。现在我需要将 Style 绑定到它的子项。

这是我想要绑定 属性:

的方式
<Window>
    <Window.Resources>
        <Style x:Key="style" TargetType="Button">
            <Setter Property="Background" Value="Red" />
        </Style>
    </Window.Resources>
    
    <Grid>
        <local:MyControl ButtonStyle="{StaticResource style}"/>
    </Grid>
</Window>

值将在 MyControl.cs 中这样设置:

public class MyControl : Control
{
    public static readonly DependencyProperty ButtonStyleProperty= DependencyProperty.Register(
        "ButtonStyle", typeof(Style), typeof(MyControl), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));

    static MyControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
    }

    public Style ButtonStyle
    {
        get => (Style)GetValue(ButtonStyleProperty);
        set => SetValue(ButtonStyleProperty, value);
    }
}

我的自定义控件的 Generic.xaml 拥有一个需要 ButtonStyleUserControl。 我试图像这样在 Generic.xaml 中传递它:

<controller:ControllerView ButtonStyle="{Binding ButtonStyle}"/>

这是 ControllerView 的隐藏代码。由于某种原因,setter 从未被访问过。

public partial class ControllerView : UserControl
{
    public static readonly DependencyProperty ButtonStyleProperty = DependencyProperty.Register(
        "ButtonStyle", typeof(Style), typeof(ControllerView), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public ControllerView()
    {
        InitializeComponent();
    }

    public Style ButtonStyle
    {
        get => (Style)GetValue(ButtonStyleProperty);
        set => SetValue(ButtonStyleProperty, value);
    }
}

它应该像这样在 ControllerView.xaml 中使用:

<Button Name="Button" Style="{Binding ButtonStyle}"
        Content="{Binding Text, Mode=OneTime}" Command="{Binding Command, Mode=OneTime}"
        Margin="1" FontSize="24">

如果有人能告诉我为什么它不能以这种方式工作,并且可能会建议我的代码的解决方案,或者可以告诉我通常如何执行此操作,那就太好了。

A Binding 默认使用 DataContext 作为来源,来自 documentation:

By default, bindings inherit the data context specified by the DataContext property, if one has been set.

依赖属性不是 DataContext 的一部分。它们在控件上定义。您可以使用 RelativeSource binding or in some cases an ElementName 来引用另一个控件进行绑定。

如果我对你的描述理解正确,MyControl 包含一个 ControllerView 并且它的 ButtonStyle 属性 应该绑定到 ButtonStyle 属性 父 MyControl.

<controller:ControllerView ButtonStyle="{Binding ButtonStyle, RelativeSource={RelativeSource AncestorType={x:Type local:MyControl}}}"/>