【发布时间】:2015-05-09 19:01:00
【问题描述】:
我们在应用程序中以 xaml 资源的形式拥有不同的图标,如下所示:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DrawingBrush x:Key="My_Icon">
<DrawingBrush.Drawing>
<GeometryDrawing Brush="Gray"> <!--I want to set this Brush here using binding-->
<GeometryDrawing.Geometry>
<GeometryGroup>
<EllipseGeometry Center="50,50" RadiusX="45" RadiusY="20" />
<EllipseGeometry Center="50,50" RadiusX="20" RadiusY="45" />
</GeometryGroup>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
而我们在另一个xaml文件中使用这些资源(在后面的代码中加载这个资源,参考下面的代码)
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
var resource = Application.Current.FindResource("My_Icon");
this.MyBrush = resource as DrawingBrush;
NewBrush = Brushes.Blue;
this.DataContext = this;
}
private DrawingBrush _myBrush;
public DrawingBrush MyBrush
{
get { return _myBrush; }
set { _myBrush = value; }
}
private Brush _newBrush;
public Brush NewBrush
{
get { return _newBrush; }
set { _newBrush = value; }
}
}
问题是,我无法使用绑定设置图标颜色(在资源代码中,第一个代码 sn-p),其属性位于 ViewModel 中(MyBrush 属性在本例中位于 Window2 代码后面)
我尝试在资源文件中使用以下代码:
<GeometryDrawing Brush="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Rectangle}, Path=NewBrush}">
但这不起作用。我可能在这里遗漏了什么。
【问题讨论】:
-
您是否包含资源字典?
-
是的。我做到了。这是我设置的灰色工作样本。我要做的就是用绑定设置这个颜色。
-
我不确定您要在这里完成什么。从您的最后一个代码 sn-p 来看,您正在尝试将
GeomertyDrawing.Brush属性绑定到Window2.MyBrush属性,该属性包含<DrawingBrush x:Key="My_Icon">",而后者又是GeometryDrawing的父级 - 这会导致循环依赖和肯定会导致异常... -
我刚刚编辑了这个问题。为错误道歉
-
你能添加一个示例项目吗?