![](/img/trans.png)
[英]WPF ControlTemplate Content Reset, when the control re-add to visual tree
[英]How can I have a ControlTemplate that only creates a container for the default, unaltered visual tree of a control?
我試圖弄清楚如何將控件的模板更改為將其保存在Grid
,如下所示:
<ControlTemplate x:Key="containedTemplate">
<Grid>
<!-- place templated control here -->
</Grid>
</ControlTemplate>
我當然希望將內部控件的任何屬性與模板控件自動同步。
可以做到嗎?
這是一個TextBox
模板的假設示例:
<ControlTemplate x:Key="textTemplate" TargetType="{x:Type TextBox}">
<Grid Background="Red">
<TextBox Name="InnerTextBox" Margin="5,5,5,5"/>
</Grid>
</ControlTemplate>
現在,如果我確實將模板應用於這樣的TextBox
實例:
<TextBox Text="{Binding MyTextProperty}" Template="{StaticResource textTemplate}"/>
...然后該控件將神奇地成為一個Grid
,其中包含一個帶有少量邊距的TextBox
,並且其Text
的屬性將綁定到任何設置了DataContext
實例的MyTextProperty
:
<!-- runtime visual tree I'd like to be produced by the above XAML -->
<Grid Background="Red">
<TextBox Text="{Binding MyTextProperty}" Margin="5,5,5,5"/>
</Grid>
如果我有以下代碼:
<StackPanel>
<TextBox Text="{Binding MyTextProperty}" Template="{StaticResource textTemplate}"/>
<TextBox Text="{Binding MyOtherTextProperty}" Template="{StaticResource textTemplate}"/>
<TextBox Text="{Binding YetAnotherTextProperty}" Template="{StaticResource textTemplate}"/>
</StackPanel>
結果樹將是這樣的:
<!-- runtime visual tree I'd like to be produced by the above XAML -->
<StackPanel>
<Grid Background="Red">
<TextBox Text="{Binding MyTextProperty}" Margin="5,5,5,5"/>
</Grid>
<Grid Background="Red">
<TextBox Text="{Binding MyOtherTextProperty}" Margin="5,5,5,5"/>
</Grid>
<Grid Background="Red">
<TextBox Text="{Binding YetAnotherTextProperty}" Margin="5,5,5,5"/>
</Grid>
</StackPanel>
在這些示例中,您可以看到TextBox
的Text
屬性正確地傳播到了“內部” TextBox
實例。 控件的默認可視樹也將保留(邊界,鍵入區域等)。
我所知道的模板部件,但正如我說,我想在這里找到一個全球性的做法,我不想改變控件的外觀; 只能將其放入容器中。
坦白說,這個問題使我筋疲力盡,我只有這個答案,但並不能說服我很多。
首先,您應該為要設置模板的每個控件創建多個ControlTemplates
,然后創建此類
public class ControlTemplateConverter
{
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(ControlTemplateConverter), new UIPropertyMetadata(false, IsEnabledChanged));
private static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ControlTemplate t;
if (d == null) return;
if (d is TextBlock)
t = App.Current.FindResource("TextBoxTemplate") as ControlTemplate;
else if (d is CheckBox)
t = App.Current.FindResource("CheckBoxTemplate") as ControlTemplate;
// and So On
(d as Control).Template = t;
}
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
}
並且您的控件應如下所示:
<TextBox local:ControlTemplateConverter.IsEnabled="True"></TextBox>
<CheckBox local:ControlTemplateConverter.IsEnabled="True"></CheckBox>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.