[英]WPF binding to ViewModel property from the DataTemplate Style
I am trying to bind ForeGround
color of all TextBlock
items to a ViewModel
property. 我试图将所有
TextBlock
项的ForeGround
颜色绑定到ViewModel
属性。 The TextBlock
elements locate under a Grid
that itself is defined under DataTemplate
. TextBlock
元素位于本身在DataTemplate
下定义的Grid
下。 This whole code is defined under a UserControl
. 整个代码在
UserControl
下定义。
I am trying to use RelativeSource
binding to find the UserControl
's DataContext
and get the property I need. 我正在尝试使用
RelativeSource
绑定来查找UserControl
的DataContext
并获取我需要的属性。
XAML: 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>
ViewModel: ViewModel:
public class MapViewModel
{
public virtual string TextColor
{
get { return _textColor; }
set
{
_textColor = value;
this.RaisePropertyChanged("TextColor");
}
}
private string _textColor = "Black";
}
The above binding doesn't work. 上面的绑定不起作用。 If I change the Value binding to a hard-coded value, like "Red" for example, the
Foreground
color on those TextBlocks
are showing correctly. 如果将“值”绑定更改为硬编码的值,例如“红色”,则这些
TextBlocks
上的Foreground
颜色将正确显示。
How to get the binding to work with this setup? 如何获得绑定才能使用此设置?
It seems the root cause — binding to an instance of the string
type instead of an instance of the Brush
type. 看来是根本原因-绑定到
string
类型的实例而不是Brush
类型的实例。
TextColor
property of the MapViewModel
class to from the string
type to the SolidColorBrush
type and update the implementation of the MapViewModel
class appropriately. MapViewModel
类的TextColor
属性的类型从string
类型更改为SolidColorBrush
类型,并适当地更新MapViewModel
类的实现。 IValueConverter
interface which takes the string
as the input and outputs an instance of the SolidColorBrush
type. IValueConverter
接口的自定义实现,该接口将string
作为输入并输出SolidColorBrush
类型的实例。 What version of .NET are you using? 您正在使用什么版本的.NET? Works fine with 4.5 but IIRC it didn't with earlier versions and you had to declare a solidcolorbrush explicitly:
在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>
Whatever you do don't create a brush or any other UI resources in your viewmodel, it's a violation of MVVM. 无论您如何在视图模型中不创建画笔或其他任何UI资源,都违反了MVVM。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.