我正在尝试将所有TextBlock
项的颜色绑定ForeGround
ViewModel
属性。TextBlock
元素位于本身在 DataTemplate
下定义的Grid
下。整个代码是在UserControl
下定义的。
我正在尝试使用RelativeSource
绑定来查找UserControl
的DataContext
并获得我需要的属性。
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
类型的实例。
一些可能的解决方案:
- 将
MapViewModel
类的TextColor
属性的类型从string
类型更改为SolidColorBrush
类型,并相应地更新MapViewModel
类的实现。 - 创建
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。