Dot-Net
是否可以在 XAML 中設置有選擇地影響控制項的樣式?
在
<Window.Resources>我定義了以下樣式:<Style x:Key="textBlockStyle" TargetType="TextBlock"> <Setter Property="Margin" Value="5,0,5,0"/> </Style>我已經定義了一些網格,其中有四個
TextBlocks:<WrapPanel> <TextBlock Style="{StaticResource textBlockStyle}">Server</TextBlock> <TextBlock Style="{StaticResource textBlockStyle}">IP</TextBlock> <TextBlock Style="{StaticResource textBlockStyle}">Port</TextBlock> <TextBlock Style="{StaticResource textBlockStyle}">Status</TextBlock> </WrapPanel>**問題:**我需要引用
textBlockStyle四次。**問題:**是否可以在不重複對樣式的引用的情況下只在其中
WrapPanel或其他地方設置一次樣式?也許是這樣的:
<WrapPanel Style="{StaticResource textBlockStyle}"> <TextBlock>Server</TextBlock> <TextBlock>IP</TextBlock> <TextBlock>Port</TextBlock> <TextBlock>Status</TextBlock> </WrapPanel>**我不是在尋找一個全球性的解決方案!**我可以刪除該
x:Key="textBlockStyle"屬性,但這會影響Window 中的所有內容。TextBlocks我需要一個更具選擇性的機制,但沒有那種醜陋的程式碼重複。
您有幾個選項,這裡按照它們的擴展程度排列。
選項 1:在較低級別定義沒有鍵的樣式
您可以將資源固定在該
WrapPanel級別,以便它僅影響其中的控制項WrapPanel:<WrapPanel> <WrapPanel.Resources> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="5,0,5,0"/> </Style> </WrapPanel.Resources> <!-- TextBlocks here --> </WrapPanel>注意缺少密鑰。這
Style將適用TextBlock於WrapPanel.選項 2:使用鍵定義樣式,然後再次在較低級別定義樣式
如果您
Style使用鍵在更高級別定義 ,則可以Style在沒有鍵的情況下在較低級別定義另一個,並將其Style基於更高級別:<Window> <Window.Resources> <Style TargetType="TextBlock" x:Key="textBlockStyle"> <Setter Property="Margin" Value="5,0,5,0"/> </Style> </Window.Resources> <WrapPanel> <WrapPanel.Resources> <Style TargetType="TextBlock" BasedOn="{StaticResource textBlockStyle"/> </WrapPanel.Resources> <!-- TextBlocks here --> </WrapPanel> </Window>這會導致 a
Style自動應用於TextBlocks 內部WrapPanel,而不是外部。此外,您不會複製的詳細資訊Style- 它們儲存在更高級別。選項 3:將樣式放在 ResourceDictionary 中並有選擇地合併它
最後,您可以將您
Style的 s 放在單獨的ResourceDictionary並有選擇地將該字典合併到控制項的Resources集合中:<!-- TextBlockStyles.xaml --> <ResourceDictionary> <Style TargetType="TextBlock"> <Setter Property="Margin" Value="5,0,5,0"/> </Style> </ResourceDictionary> <!-- Window.xaml --> <Window> <WrapPanel> <WrapPanel.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="TextBlockStyles.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </WrapPanel.Resources> </WrapPanel> </Window> <!-- Alternative Window.xaml if you have only one RD to merge in --> <Window> <WrapPanel> <WrapPanel.Resources> <ResourceDictionary Source="TextBlockStyles.xaml"/> </WrapPanel.Resources> </WrapPanel> </Window>現在,您可以根據需要在單獨的字典中定義任意數量的樣式集,然後有選擇地將它們應用於您的元素樹。