1

如何<Color x:Key="SomeColor" />使用 Caliburn Micro 将类似的东西绑定到依赖属性?

我需要能够Color在运行时进行更改,并在所有使用它的东西中立即更新它。

解决方案:


SomeClassView.xaml 中的 XAML

<SomeControl.Resources>
    <SolidColorBrush x:Key="ControlBrush" />
</SomeControl.Resources>

SomeClassViewModel.cs 中的 C#

[Export(typeof(MainWindowViewModel))]
public class MainWindowViewModel : PropertyChangedBase
{
    private SolidColorBrush _controlBrush;

    public SolidColorBrush ControlBrush
    {
        get { return _controlBrush; }
        set
        {
            _controlBrush = value;
            NotifyOfPropertyChange(() => ControlBrush);
        }
    }
}

问题正是 Charleh 所说的,我完全忘记了并非 WPF 中的所有内容都可以是 DependencyProperty。

4

1 回答 1

3

您通常不能直接绑定Color对象,您需要使用 a SolidColorBrush(用于纯色),因为这是大多数 UI 对象所期望的。

例如

TextBox.Background期望Brush,它SolidColorBrush是的子类。还有其他类型的刷子可以产生不同的填充,例如LinearGradientBrush

看看这里:

如何在 WPF/XAML 中绑定背景颜色?

您能否提供一些您所期望的和 XAML 的屏幕截图?

编辑:

好吧,你想要的很容易实现,与 Caliburn.Micro 完全没有关系:)

像往常一样创建你的样式,但是Color使用动态绑定画笔属性DynamicResource。当您更新颜色本身时,将再次评估资源绑定并且颜色将发生变化。

示例 XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Color x:Key="TestColor" A="255" R="255" G="0" B="0"></Color>
        <Style x:Key="ButtonStyle" TargetType="Button">
            <Setter Property="Background">
                <Setter.Value>
                    <SolidColorBrush Color="{DynamicResource TestColor}"></SolidColorBrush>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <Button Click="Button_Click" Style="{StaticResource ButtonStyle}">Red</Button>
            <Button Click="Button_Click_1" Style="{StaticResource ButtonStyle}">Blue</Button>
        </StackPanel>
    </Grid>
</Window>

代码隐藏:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Resources["TestColor"] = Color.FromArgb(255, 255, 0, 0);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Resources["TestColor"] = Color.FromArgb(255, 0, 0, 255);
        }
    }
}
于 2012-12-08T19:02:11.197 回答