简体   繁体   English

WPF / C#将两个变量链接在一起

[英]WPF/C# Link Two Variables together

I currently have a simple WPF application, in the MainWindow I will have a variable (In this case the variable is a class that holds data). 我目前有一个简单的WPF应用程序,在MainWindow中,我将有一个变量(在这种情况下,变量是一个保存数据的类)。 Then I have a User Control which has the same variable. 然后,我有一个具有相同变量的用户控件。 Currently, I'm passing the variable with the ref keyword and it works perfectly fine, however, is this save/good practice? 目前,我正在使用ref关键字传递变量,并且效果很好,但是,这是保存/好的做法吗? Is there a better way of linking this two variables together? 是否有更好的方法将这两个变量链接在一起?

I am aware of the existence of DependencyProperty, however, I could not get it to work. 我知道DependencyProperty的存在,但是我无法使其正常工作。

MainWindow: 主窗口:

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: TestGridUI:

public partial class TestGridUC : UserControl {
        private TestClassWithInfo m_SelectedInfo;

        public TestGridUC (ref TestClassWithInfo e)
        {
            InitializeComponent();
            m_SelectedInfo = e;
        }
}

TestClassWithInfo: TestClassWithInfo:

public class TestClassWithInfo 
{
    public Image imageTest;
    public int intTest;


    public TestClassWithInfo ()
    {
        m_img = null;
        m_layer = 0;
    }
}

I am aware of the existence of DependencyProperty, however, I could not get it to work. 我知道DependencyProperty的存在,但是我无法使其正常工作。

A dependency property really is the way to go about it though: 依赖属性确实是解决该问题的方法:

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()*/ ));
}

Now you can bind to that property from the xaml in your MainWindow: 现在,您可以从MainWindow中的xaml绑定到该属性:

    <local:TestGridUC
        Info="{Binding Info}"></local:TestGridUC>

If you need help with that part, as pr177 answered there are many tutorials on getting started with WPF with the MVVM pattern. 如果您需要有关那部分的帮助,请按pr177的回答,有许多关于MVVM模式的WPF入门的教程。 The basics here would involve a view model object that contains a TestClassWithInfo public property that you bind to. 这里的基础知识将涉及一个视图模型对象,该对象包含绑定到的TestClassWithInfo公共属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM