我是WPF的新手。我面临以下问题。我有一个用户控件,这是用户控制代码
CustomControl代码
public partial class CustomCanvas : UserControl
{
public CustomCanvas()
{
InitializeComponent();
DrawCanvas();
}
private void DrawCanvas()
{
//TODO:
//Get the Dictionary Value from Parent Bound Property
}
public Dictionary<string, List<Shapes>> ShapesData
{
get { return (Dictionary<string, List<Shapes>>)GetValue(ShapesDataProperty); }
set { SetValue(ShapesDataProperty, value); }
}
public static readonly DependencyProperty ShapesDataProperty =
DependencyProperty.Register("ShapesData", typeof(Dictionary<string, List<Shapes>>), typeof(CustomCanvas), new PropertyMetadata(ShapesDataChanged));
private static void ShapesDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var value = e.NewValue;
}
}
主窗口代码
<Grid>
<uc:CustomCanvas ShapesData="{Binding ShData}" ></uc:CustomCanvas>
</Grid>
ShapesData的值受以下代码约束。
ShData = new Dictionary<string, List<Shapes>>()
{
{"Week 1", new List<Shapes>() {Shapes.Circle, Shapes.Rectangle}},
{"Week 2", new List<Shapes>() {Shapes.Circle}},
{"Week 3", new List<Shapes>() {Shapes.Rectangle}}
};
现在我的问题是在CustomControl DrawCanvas 方法中我想获取父级中的有界值。任何人都可以指导我。
P.S :我知道如何使用相对RelativeSource和Mode作为FindAncestor将此值绑定在child中。在这里,我想获取值并处理该词典数据。在 ShapesDataChanged 中,我可以轻松访问数据,但问题是在DrawCanvas函数中获取它。
提前致谢。
答案 0 :(得分:2)
您可以使用DependencyObject的GetValue()方法。
var theValueYouNeeded = CustomCanvas.GetValue(ShapesDataProperty);
Dictionary<string, List<Shapes>> value = (Dictionary<string, List<Shapes>>)theValueYouNeeded;
....