【发布时间】:2012-08-28 22:30:04
【问题描述】:
我的一个视图由 5 个UserControls 组成,每个视图都显示有关某个对象的数据。例如,假设视图显示了我们公司拥有的奶牛,并且在屏幕上显示了奶牛 1 到 5(每个都在自己的 UserControl 中)。
我想做的(但不确定是否可能)是将牛的状态绑定到其各自的 UserControl 中使用的样式。所以我们有一个属性status,例如可以是ok、hungry、dead。如果奶牛是ok,我想显示“正常”样式,如果是hungry,我希望背景为红色,如果是dead,我希望文本为黑色并增加字体大小。
我添加了我想要实现的简化版本。不过,我对 WPF 样式/资源字典的了解仍然有限。
我基本上想要的代码
具有 Status 属性的 ViewModel
class CowInfoViewModel : Screen
{
public string Name { get; set; }
public string Status { get; set; } //"ok", "hungry", "dead"
}
检索样式或资源字典的视图
<UserControl x:Class="WpfModifyDifferentView.Views.CowInfoView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- A reference to a ResourceDictionary with styles, that is bound to the 'Status' property -->
<StackPanel>
<TextBlock x:Name="Name" Text="Cow Name"/>
<TextBlock x:Name="Status" Text="Ok" />
</StackPanel>
</UserControl>
编辑 - 解决方案:
我使用 Vale 的回答做了以下事情:
在xaml中(引用转换器):
<UserControl.Resources>
<Converters:CowStyleConverter x:Key="styleConverter" />
</UserControl.Resources>
在xaml(元素)中:
<TextBlock x:Name="Name" Text="Cow Name" Style="{Binding Path=Style, ConverterParameter='TextBlockCowName', Converter={StaticResource styleConverter}}" />
转换器(注意我省略了检查):
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var status = value.ToString();
var styleName = parameter.ToString();
_resourceDictionary.Source = new System.Uri(string.Format("pack://application:,,,/Resources/ScreenI2Style{0}.xaml", status));
return _resourceDictionary[styleName];
}
然后我创建了多个 ResourceDictionaries,其样式如下:
<Style x:Key="TextBlockCowName" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource SomeBrush}" />
</Style>
【问题讨论】:
标签: c# wpf caliburn.micro