如何将 CustomControl 属性 绑定到控件本身?

How do I bind a CustomControl Property to the control itself?

这是我问的问题的后续问题 -

控件 class 具有依赖项 属性 -

private static readonly DependencyProperty
    _Color = DependencyProperty.Register( "Color", typeof( Color ), typeof( ColorDefiner ), new PropertyMetadata( Colors.Black ) );

public Color Color {
    get { return ( Color )this.GetValue( ColorDefiner._Color ); }
    set { this.SetValue( ColorDefiner._Color, value ); }
}

在控件 XAML 中,如何访问 属性 以便我可以将其双向绑定到负责定义颜色 属性 的控件滑块?

编辑

这是其中一个滑块的代码 -

<Slider
    x:Name="sdrRed" Height="32" Minimum="0" Maximum="1" Width="294" TickPlacement="Both"
    TickFrequency="0.01" Value="{Binding Color, Mode=TwoWay, ElementName=Me}">
</Slider>

MeUserControl 的名称。我的想法是问题是因为我指向 Color.ScR

我认为我需要使用滑块值属性将颜色 属性 绑定到 MultiBinding,而不是将滑块的值绑定到颜色 属性。

编辑

我觉得这是我应该实现 MVVM 的地方 - 谁能告诉我我如何在这里实现它?

如果我理解得很好,你有一个 userControl,里面有滑块。 这就是我在 Xaml 中的做法,请执行以下操作。

<UserControl x:Name="MultiSlider">
...
<Slider Color="{Binding Color, ElementName="MultiSlider"}.../>
...
</UserControl>

与其他属性和其他滑块相同。

已添加

在用户控件中您需要添加 4 个依赖属性:

public Color Color
    {
        get { return (Color)GetValue(ColorProperty); }
        set { SetValue(ColorProperty, value); }
    }

    public static readonly DependencyProperty ColorProperty =
        DependencyProperty.Register("Color", typeof(Color), typeof(MySlider), new PropertyMetadata(Colors.Red));

以及其余属性

public double RValue
    {
        get { return (double)GetValue(RValueProperty); }
        set { SetValue(RValueProperty, value); }
    }

    public static readonly DependencyProperty RValueProperty =
        DependencyProperty.Register("RValue", typeof(double), typeof(MySlider), new PropertyMetadata(0, ValueChanged));

    private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var currentColor = (d as MySlider).Color;
        var newcolor = new Color() { R = (byte)e.NewValue, B = currentColor.B, G = currentColor.G };
        (d as MySlider).Color  = newcolor;
    }

然后是绿色和蓝色,注意 NewValue 的转换我不知道滑块范围是否达到 255。

如果我对您的理解正确,您希望将 ColorDefiner.Color 属性 多重绑定到 ColorDefiner 本身内的滑块。为了在 XAML 中执行此操作,您需要使用样式(由于样式的目标类型限制,您还需要指定完全限定的 属性 名称):

<UserControl ...>
    <UserControl.Style>
        <Style>
            <Setter Property="local:ColorDefiner.Color">
                <MultiBinding Converter="{StaticResource colorConverter}">
                    <Binding ElementName="sdrAlpha" Path="Value" Mode="TwoWay" />
                    <Binding ElementName="sdrRed" Path="Value" Mode="TwoWay" />
                    <Binding ElementName="sdrGreen" Path="Value" Mode="TwoWay" />
                    <Binding ElementName="sdrBlue" Path="Value" Mode="TwoWay" />
                </MultiBinding>
            </Setter>
        </Style>
    <UserControl.Style>
    <!-- sliders -->
</UserControl>

虽然这种方法有一个巨大的缺点 - 如果最终用户为控件设置样式或在 Color 属性 上设置自定义出价,则多重绑定将丢失。另一方面,如果最终用户为控件设置自定义内容,则滑块将消失。这就是为什么在这种情况下你真的应该考虑使用 CustomControl 和模板而不是 UserControl 并在代码隐藏中组合输出颜色。