如果我有一個簡單的子控制元件,它已經為子控制元件中的元素定義了樣式。我可以從父控制元件更改該元素的樣式嗎?
如果我不在子控制元件中設定樣式,我可以從父控制元件覆寫它,但是在設定樣式時我似乎無法讓它作業。
我無法更改子控制元件中的代碼。
示例子控制元件:
<UserControl
x:Class="TestingThemes.ChildControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestingThemes"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<UserControl.Resources>
<Style x:Key="aw" TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
</Style>
</UserControl.Resources>
<Grid>
<Button
Width="100"
Height="50"
Content="Kalle Anka"
<!-- If I remove the style I can override it from parent control -->
Style="{DynamicResource aw}" />
</Grid>
</UserControl>
家長控制:
<Grid>
...
<local:ChildControl>
<local:ChildControl.Resources>
<!--<Style BasedOn="{StaticResource local:ResourceKey=aw}" TargetType="Button">-->
<Style TargetType="Button">
<Setter Property="Foreground" Value="Red" />
</Style>
</local:ChildControl.Resources>
</local:ChildControl>
</Grid>
uj5u.com熱心網友回復:
這是可能的,但您必須更改初始Style. 的XAML引擎將遍歷邏輯樹,以查找StaticResource/DynamicResource資源元素(例如,Button區域地開始),與本地ResourceDictionary。
這意味著,您希望在查找路由的最后找到在Style內定義的默認值UserControl- 在任何旨在覆寫默認值的潛在自定義樣式之后Style。為此,您必須將 移動Style到App.xaml或Generic.xaml。
此外,參考必須是DynamicResource為了將查找推遲到組成邏輯樹的那一刻。Style可以在通往樹根的路線上的任何位置定義覆寫。
由于Generic.xaml提供了不同的名稱范圍,您必須定義一個唯一的靜態(就 XAML 名稱范圍而言是全域的)ComponentResourceKey,您必須將其用作樣式的x:Key值(以防您計劃將默認樣式移動到Generic.xaml檔案)。
由于前面提到的 XAML 資源查找行為,當您計劃使控制元件可自定義(就像您的情況一樣)時,創建自定義Control始終比 a 更可取UserControl。默認情況下Style,自定義的默認值Control位于Generic.xaml 中,因此您永遠不會遇到當前的問題。
子控制元件.xaml
<UserControl>
<Grid>
<Button Style="{DynamicResource aw}" />
</Grid>
</UserControl>
App.xaml中
前的最后查找位置Generic.xaml。如果Style尚未找到具有相同鍵的a ,則將應用Style找到的 in App.xaml。
<Style x:Key="aw" TargetType="Button">
<Setter Property="Foreground" Value="Blue" />
</Style>
父控制元件.xaml
<ChildControl>
<ChildControl.Resources>
<Style x:Key="aw" TargetType="Button">
<Setter Property="Foreground" Value="Red" />
</Style>
</ChildControl.Resources>
</ChildControl>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355769.html
上一篇:Python-附加到檔案串列
