WPF 从数据模板样式绑定到 ViewModel 属性



我正在尝试将所有TextBlock项的颜色绑定ForeGround ViewModel属性。TextBlock元素位于本身在 DataTemplate 下定义的Grid下。整个代码是在UserControl下定义的。

我正在尝试使用RelativeSource绑定来查找UserControlDataContext并获得我需要的属性。

XAML:

<my:MapControl>
    <my:MapControl.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="SomeTemplate">
                <Grid>
                     <Grid.RowDefinitions>
                          <RowDefinition />
                          <RowDefinition />
                     </Grid.RowDefinitions>
                     <Grid.Style>
                         <Style TargetType="Grid">
                              <Setter Property="TextElement.Foreground" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.TextColor}" />
                         </Style>
                     </Grid.Style>
                     <TextBlock Grid.Column="0" />
                     <TextBlock Grid.Column="1" />
                </Grid>
            </DataTemplate>
        </ResourceDictionary>
    </my:MapControl.Resources>
</my:MapControl>

视图模型:

public class MapViewModel
{
    public virtual string TextColor
    {
        get { return _textColor; }
        set
        {
            _textColor = value;
            this.RaisePropertyChanged("TextColor");
        }
    }
    private string _textColor = "Black";
}

上述绑定不起作用。如果我将 Value 绑定更改为硬编码值(例如"红色"(,则这些TextBlocks上的Foreground颜色将正确显示。

如何使绑定与此设置一起使用?

分析

这似乎是根本原因 — 绑定到 string 类型的实例而不是 Brush 类型的实例。

一些可能的解决方案:

  1. MapViewModel 类的 TextColor 属性的类型从string类型更改为SolidColorBrush类型,并相应地更新 MapViewModel 类的实现。
  2. 创建 IValueConverter 接口的自定义实现,该接口将string作为输入并输出 SolidColorBrush 类型的实例。

您使用的是哪个版本的 .NET?在 4.5 中工作正常,但 IIRC 在早期版本中则不然,您必须显式声明一个 solidcolorbrush:

<Style TargetType="Grid">
    <Setter Property="TextElement.Foreground">
        <Setter.Value>
            <SolidColorBrush Color="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.TextColor}" />
        </Setter.Value>
    </Setter>
</Style>

无论您做什么,都不要在视图模型中创建画笔或任何其他 UI 资源,这都违反了 MVVM。

最新更新