获取UserControl代码隐藏中的依赖项属性值
本文关键字:依赖 属性 UserControl 代码 隐藏 获取 | 更新日期: 2023-09-27 18:29:59
我是WPF的新手。我面临以下问题。我有一个用户控制,这是用户控制的代码
自定义控制代码
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}}
};
现在我的问题是,在CustomControlDrawCanvas方法中,我想获取父对象中的有界值。有人能为我提供这方面的指导吗。
p.S:我知道如何使用相对的RelativeSource和Mode作为FindAncestor在child中绑定此值。在这里,我只想获取值并处理Dictionary数据。在ShapesDataChanged中,我可以很容易地访问数据,但问题是在DrawCanvas函数中获取数据。
提前谢谢。
您可以使用DependencyObject的GetValue()方法。
var theValueYouNeeded = CustomCanvas.GetValue(ShapesDataProperty);
Dictionary<string, List<Shapes>> value = (Dictionary<string, List<Shapes>>)theValueYouNeeded;
....