我有这个XML文件:
<?xml version="1.0" encoding="utf-8"?>
<Wpf>
<wpfctrl id="NavBtnTemplate">#FFCFDEFF</wpfctrl>
</Wpf>
我希望将My Rectangle的Fill属性绑定到id =“NavBtnTemplate”的wpfctrl节点的值。我怎么能做到这一点?实际上我在自定义UserControl的控件模板中有这个矩形。但希望不会出现问题,因为我可以绑定到UserControl中的元素属性: 我的UserControl(实际上非常简单)
<UserControl.Resources>
<ControlTemplate x:Key="WpfWebSparkNavTemplate" TargetType="{x:Type Button}">
<Grid x:Name="controlLayout" Height="29.648" Width="84.284">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Pressed"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Rectangle x:Name="rectangle"***Fill="#FFCFDEFF"*** Margin="0" Height="31">
</Rectangle>
<Label x:Name="buttonCaption" VerticalAlignment = "Center"
HorizontalAlignment = "Center"
FontWeight = "Bold" FontSize = "12" Content="{TemplateBinding Content}"/>
</Grid>
</ControlTemplate>
</UserControl.Resources>
我没有找到Blend向导允许我在XML上说明这样的过滤器
请帮忙。谢谢。
答案 0 :(得分:0)
如果我理解正确,你想在UserControl中将Rectangle的Fill属性绑定到你在XAML中声明UserControl实例时设置(或绑定)的属性。
您要做的第一件事是在您的用户控件上有一个Fill属性,因此在UserControl的代码后面创建一个DependencyProperty:
public static readonly DependencyProperty FillProperty =
DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(UserControl1));
public Brush Fill
{
get { return (Brush)GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
有了这个,您可以修改ControlTemplate,以便矩形Fill属性绑定到此DependencyProperty(适当地更改WpfApplication1名称空间):
<Rectangle x:Name="rectangle" Fill="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=WpfApplication1:UserControl1}, Path=Fill}" Margin="0" Height="31"/>
然后您可以按如下方式使用您的控件:
<WpfApplication1:UserControl1 Grid.Row="1" Fill="Red"/>
接下来要做的是绑定UserControl的Fill属性。您需要为XML文件创建数据源,例如:
<Window.Resources>
<XmlDataProvider x:Key="xmlData" Source="XMLFile1.xml"/>
</Window.Resources>
然后绑定到数据源:
<WpfApplication1:UserControl1 Grid.Row="0">
<WpfApplication1:UserControl1.Fill>
<Binding Source="{StaticResource xmlData}"
XPath="//wpfctrl[@id='NavBtnTemplate']"/>
</WpfApplication1:UserControl1.Fill>
</WpfApplication1:UserControl1>