我正在试图找出如何将控件的模板更改为将其保存在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实例,控件的默认视觉树也被保留下来(边框、键入区域等)。
我知道模板部件,但正如我所说的,我在这里试图找到一种全局方法,而且我不希望改变控件的外观,只将它放在容器中。
发布于 2015-01-19 20:53:38
坦率地说,这个问题使我筋疲力尽,我只有这个答案,但没有说服我太多。
首先,您应该为要设置模板的每个控件创建多个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>https://stackoverflow.com/questions/28031241
复制相似问题