我的一個視圖由5個UserControls
組成,每個視圖顯示有關某個對象的數據。比方說,視圖顯示我們公司擁有的奶牛,並在屏幕上顯示奶牛1到5(每個奶牛都在他們自己的UserControl中)。將屬性綁定到視圖的style/resourcedictionary
我想做什麼(但不能確定是可能的)是將牛的狀態綁定到其各自UserControl中使用的樣式。因此,我們有一個屬性status
,可能是ok
,hungry
,dead
例如。如果牛是ok
我想要顯示'正常'風格,如果它是hungry
我想要背景爲紅色,並且如果它是dead
我希望文本爲黑色並且字體大小增加。
我已經添加了我想要實現的簡化版本。儘管如此,我對WPF樣式/資源字典的瞭解仍然有限。
我基本上要在代碼
一個ViewModel與Status
財產
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>
編輯視圖 - 解決方案:
我做了使用淡水河谷的回答如下:
在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];
}
然後我創建了多個資源字典,其樣式如下:
<Style x:Key="TextBlockCowName" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource SomeBrush}" />
</Style>
感謝您的回答:)目前在我工作的地方出現了其他一些問題。我會盡快嘗試這個 – Deruijter
再次感謝您的答案,我只是試了一下,它很好地工作:)我只是想知道是否有可能改變多個元素的風格? (對於某些特定元素,樣式總是具有'TargetType')?例如,我想升級UserControl,Grid,Borders和TextBlocks,但(afaik)每個元素都需要不同的樣式元素。這是否意味着我必須在'Status'事件中有一個額外的switch語句才能獲得各個元素的樣式? – Deruijter
是的,如果您正在爲該類型做特定的事情,則需要不同的風格。但是,如果您想更改一般(基本)屬性,則可以將TargetType設置爲Control或FrameworkElement。是的,如果要在不同風格的不同類型上使用相同的轉換器,則可以檢查switchType語句中的targetType參數。 – Vale