本文介绍了将颜色属性从 xaml 绑定到 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将自制控件的属性从我的视图绑定到我的视图模型.当我将颜色直接绑定到 xaml 中的另一个元素时,它可以工作,但是当我尝试将它绑定到我的视图模型中的属性时.属性没有变化.

I am trying to bind a property of a self made control from my view to my viewmodel. When I bind the color directly to another element in the xaml, it works but when i try to bind it to a property in my viewmodel. There is not change in property.

xml:

<StackPanel>
    <Border Height="50"
            BorderBrush="Black"
            BorderThickness="1">
        <Border.Background>
            <SolidColorBrush Color="{Binding color}" />
        </Border.Background>
    </Border>
    <Border Height="50"
            BorderBrush="Black"
            BorderThickness="1">
        <Border.Background>
            <SolidColorBrush Color="{Binding ElementName=colorCircle, Path=selectedColor}" />
        </Border.Background>
    </Border>

    <local:ColorCircle x:Name="colorCircle" selectedColor="{Binding color, Mode=OneWayToSource}" />

</StackPanel>

.cs:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private Color _color;
    public Color color
    {
        get { return _color; }
        set
        {
            _color = value;
            RaisePropertyChanged("color");
        }
    }

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
    }

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

色轮

xml:

<Grid HorizontalAlignment="Center"
      VerticalAlignment="Center"
      Background="Transparent">

    <Image x:Name="ColorImage"
           Width="300"
           Height="300"
           HorizontalAlignment="Center"
           VerticalAlignment="Top"
           RenderOptions.BitmapScalingMode="HighQuality"
           Source="color_wheel.png" />

    <Canvas x:Name="CanvImage"
            Width="300"
            Height="300"
            HorizontalAlignment="Center"
            VerticalAlignment="Top"
            Background="Transparent">

        <Ellipse Width="300"
                 Height="300"
                 HorizontalAlignment="Center"
                 VerticalAlignment="Top"
                 Fill="Transparent"
                 MouseDown="Ellipse_MouseDown"
                 MouseMove="Ellipse_MouseMove"
                 MouseUp="Ellipse_MouseUp" />
        <Ellipse x:Name="ellipsePixel"
                 Canvas.Left="150"
                 Canvas.Top="150"
                 Width="10"
                 Height="10"
                 Fill="Transparent"
                 MouseDown="Ellipse_MouseDown"
                 MouseMove="Ellipse_MouseMove"
                 MouseUp="Ellipse_MouseUp"
                 Stroke="Black"
                 StrokeThickness="2" />
    </Canvas>
</Grid>

.cs:

public partial class ColorCircle : UserControl
{
    public static readonly DependencyProperty SelectedColorProperty =
        DependencyProperty.Register("selectedColor", typeof(SolidColorBrush), typeof(ColorCircle));

    private SolidColorBrush _selectedColor = new SolidColorBrush(Colors.Transparent);
    public SolidColorBrush selectedColor
    {
        get { return (SolidColorBrush)GetValue(SelectedColorProperty); }
        set
        {
            if (_selectedColor != value)
            {
                SetValue(SelectedColorProperty, value);
            }
        }
    }

    private bool __isMouseDown { get; set; } = false;
    private bool _isMouseDown
    {
        get { return __isMouseDown; }
        set
        {
            __isMouseDown = value;
            if (__isMouseDown) ColorSelect();
        }
    }

    public ColorCircle()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void ColorSelect()
    {
        try
        {
            CroppedBitmap cb = new CroppedBitmap(ColorImage.Source as BitmapSource,
                new Int32Rect((int)Mouse.GetPosition(CanvImage).X,
                    (int)Mouse.GetPosition(CanvImage).Y, 1, 1));

            byte[] pixels = new byte[4];

            try
            {
                cb.CopyPixels(pixels, 4, 0);
            }
            catch (Exception) { }

            ellipsePixel.SetValue(Canvas.LeftProperty, Mouse.GetPosition(CanvImage).X - 5);
            ellipsePixel.SetValue(Canvas.TopProperty, Mouse.GetPosition(CanvImage).Y - 5);
            CanvImage.InvalidateVisual();
            selectedColor = new SolidColorBrush(Color.FromArgb(255, pixels[2], pixels[1], pixels[0]));

        }
        catch (Exception) { }
    }

    private void Ellipse_MouseMove(object sender, MouseEventArgs e)
    {
        if (_isMouseDown) ColorSelect();
    }

    private void Ellipse_MouseDown(object sender, MouseButtonEventArgs e)
    {
        _isMouseDown = true;
    }

    private void Ellipse_MouseUp(object sender, MouseButtonEventArgs e)
    {
        _isMouseDown = false;
    }
}

colorcircle 有一个 DependencyProperty selectedColor 返回一个 Color.这样可行.我在第二个边框中获得颜色,但在第一个边框中没有......

The colorcircle has a DependencyProperty selectedColor that returns a Color. That works. I get the color in the second border but not in the first one...

推荐答案

我找到了失败的原因.我需要将 ColorCircle 的DataContext"设置为this"的DataContext".

I found the reason it failed. I needed to set the 'Datacontext' of the ColorCircle to the 'DataContext' of 'this'.

<local:ColorCircle x:Name="colorCircle"
                       Grid.Row="1"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Bottom"
                       DataContext="{Binding .}"
                       selectedColor="{Binding selectedColorXaml,
                                               Mode=TwoWay}" />

所以 'DataContext="{Binding .}"' 是答案...

so 'DataContext="{Binding .}"' was the anwser...

这篇关于将颜色属性从 xaml 绑定到 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:07