【问题标题】:WPF binding to ViewModel property from the DataTemplate StyleWPF 从 DataTemplate 样式绑定到 ViewModel 属性
【发布时间】:2016-01-11 15:35:55
【问题描述】:

我正在尝试将所有TextBlock 项目的ForeGround 颜色绑定到ViewModel 属性。 TextBlock 元素位于 Grid 下,而 Grid 本身在 DataTemplate 下定义。整个代码在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 颜色将正确显示。

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

【问题讨论】:

  • 你在粘贴忘记实现INPC接口的代码时删除了它:MapViewModel: INotifyPropertyChanged。如果这只是简化,那么您确定 MapViewModel 是您的 UserControlDataContext 吗?
  • 如果在TextColor属性的get中放了一个断点,是否调用?观察输出窗口 (Ctrl+Alt+O) 中与 DataBinding 相关的任何错误消息。按照 dkozl 的建议检查 DataContext 的分配。问候

标签: wpf xaml mvvm binding datatemplate


【解决方案1】:

分析

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

一些可能的解决方案:

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

【讨论】:

    【解决方案2】:

    您使用的是哪个版本的 .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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2021-05-21
      • 2020-12-15
      • 2021-04-20
      相关资源
      最近更新 更多