[英]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.