简体   繁体   中英

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). 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? 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.

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:

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;
    }
}

I am aware of the existence of DependencyProperty, however, I could not get it to work.

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:

    <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. The basics here would involve a view model object that contains a TestClassWithInfo public property that you bind to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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