[英]WPF/C# Link Two Variables together
我目前有一个简单的WPF应用程序,在MainWindow中,我将有一个变量(在这种情况下,变量是一个保存数据的类)。 然后,我有一个具有相同变量的用户控件。 目前,我正在使用ref关键字传递变量,并且效果很好,但是,这是保存/好的做法吗? 是否有更好的方法将这两个变量链接在一起?
我知道DependencyProperty的存在,但是我无法使其正常工作。
主窗口:
public partial class MainWindow : Window
{
private TestClassWithInfo m_SelectedInfo;
public MainWindow()
{
InitializeComponent();
m_SelectedInfo = new DrawingInformation();
TestGridUC mp = new TestGridUC(ref m_SelectedInfo);
TestCanvas.Childrens.Add(mp);
}
}
TestGridUI:
public partial class TestGridUC : UserControl {
private TestClassWithInfo m_SelectedInfo;
public TestGridUC (ref TestClassWithInfo e)
{
InitializeComponent();
m_SelectedInfo = e;
}
}
TestClassWithInfo:
public class TestClassWithInfo
{
public Image imageTest;
public int intTest;
public TestClassWithInfo ()
{
m_img = null;
m_layer = 0;
}
}
我知道DependencyProperty的存在,但是我无法使其正常工作。
依赖属性确实是解决该问题的方法:
public partial class TestGridUC : UserControl
{
public TestGridUC()
{
InitializeComponent();
}
public TestClassWithInfo Info
{
get { return (TestClassWithInfo)GetValue(InfoProperty); }
set { SetValue(InfoProperty, value); }
}
public static readonly DependencyProperty InfoProperty =
DependencyProperty.Register("Info", typeof(TestClassWithInfo), typeof(TestGridUC),
new PropertyMetadata(null /*or initialize to a default of new TestClassWithInfo()*/ ));
}
现在,您可以从MainWindow中的xaml绑定到该属性:
<local:TestGridUC
Info="{Binding Info}"></local:TestGridUC>
如果您需要有关那部分的帮助,请按pr177的回答,有许多关于MVVM模式的WPF入门的教程。 这里的基础知识将涉及一个视图模型对象,该对象包含绑定到的TestClassWithInfo
公共属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.