[英]Sharing styles between several GridView controls
我需要在整個應用程序中使用相同的視覺樣式設置幾個GridView
樣式。 這種風格包括自定義ItemsPanel
屬性還有GroupStyle
財產。
我的問題是GridView
的GroupStyle
屬性不是依賴屬性。 所以我想寫的代碼(見下文)不起作用。
您是否知道在幾個GridView
之間共享樣式(包括GroupStyle
)的簡潔方法?
我唯一能想到的就是使用GroupStyleSelector
但它有點愚蠢,因為沒有選擇:它總是與正在使用的GroupStyle
相同。 此外,我懷疑它不會在VS&Blend的設計時反映出來。
我想用的代碼:
<GridView
ItemsSource="..."
ItemTemplate="..."
Style="{StaticResource MainMenuStyle}"/>
<Style TargetType="GridView" x:Key="MainMenuStyle">
<Setter Property="ItemsPanel">
<Setter.Value>
...
</Setter.Value>
</Setter>
<Setter Property="GroupStyle">
<Setter.Value>
<GroupStyle>
...
</GroupStyle>
</Setter.Value>
</Setter>
</Style>
我有一個神奇的快樂解決方案。
您可以創建在樣式中設置的自定義附加屬性,並在設置內部時在GridView上設置GroupStyle屬性。
附屬物:
// Workaround for lack of generics in XAML
public class GroupStyleCollection : Collection<GroupStyle>
{
}
public class GroupStyleHelper
{
public static ICollection<GroupStyle> GetGroupStyle(ItemsControl obj)
{
return (ICollection<GroupStyle>)obj.GetValue(GroupStyleProperty);
}
public static void SetGroupStyle(ItemsControl obj, ICollection<GroupStyle> value)
{
obj.SetValue(GroupStyleProperty, value);
}
public static readonly DependencyProperty GroupStyleProperty =
DependencyProperty.RegisterAttached(
"GroupStyle",
typeof(ICollection<GroupStyle>),
typeof(GroupStyleHelper),
new PropertyMetadata(null, OnGroupStyleChanged));
private static void OnGroupStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsControl itemsControl = d as ItemsControl;
if (itemsControl == null)
return;
RefreshGroupStyle(itemsControl, GetGroupStyle(itemsControl));
}
private static void RefreshGroupStyle(ItemsControl itemsControl, IEnumerable<GroupStyle> groupStyle)
{
itemsControl.GroupStyle.Clear();
if (groupStyle == null)
return;
foreach (var item in groupStyle)
{
itemsControl.GroupStyle.Add(item);
}
}
}
XAML風格:
<Style TargetType="ItemsControl">
<Setter Property="GroupStyleTest:GroupStyleHelper.GroupStyle">
<Setter.Value>
<GroupStyleTest:GroupStyleCollection>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock FontWeight="Bold" FontSize="15" Text="{Binding Path=Name}" Foreground="HotPink"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</GroupStyleTest:GroupStyleCollection>
</Setter.Value>
</Setter>
</Style>
免責聲明:我在WPF而不是WinRT中測試它,但據我所知,它應該是相同的。 這也是我使用ItemsControl而不是GridView的原因,但無論如何屬性都是ItemsControl.GroupStyle。
我有一個解決方案,肯定會按照你的問題工作,但你應該決定是否在你的情況下使用它。
如果你必須在整個項目中制作相同的控件樣式,那么你應該創建一個公共文件夾並在該文件夾中創建一個“自定義用戶控件”並應用你所有的樣式並根據需要自定義它。
之后,當您需要在同一控件(任何網格控件)上應用相同類型的樣式時,只需添加該自定義用戶即可
控制而不是預定義的控制
通過這樣做,您還將實現MVC架構和模塊化。
我正在使用XAML在C#中開發Windows 8 Metro應用程序,並且每當我想要這種方法時,我總是使用這個解決方案,它始終有效......
要創建自定義用戶控件,您應該使用visual studio & 右鍵單擊項目 - >添加 - >新項 - >用戶控件
(對不起,如果你在這里找不到你的解決方案,但我認為這可能有幫助...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.