我想将类的属性绑定到我的用户控件中的控件

时间:2013-01-29 10:29:14

标签: c# wpf binding wpf-controls

我很难找到解决我的约束问题的方法。

我有一个用户控件,它有一个用于调用单独窗口的按钮,用户可以在其中选择一个对象。选择此对象后,窗口关闭,用户控件中的对象根据选择更新其属性。 此对象的属性绑定到用户控件中的控件,但是当我更新对象中的属性时,控件中的值不会更新(我希望这是有意义的)。

这里有一个精简的代码:

public partial class DrawingInsertControl : UserControl
{
    private MailAttachment Attachment { get; set; }        

    public DrawingInsertControl(MailAttachment pAttachment)
    {
        Attachment = pAttachment;

        InitializeComponent();

        this.DataContext = Attachment;
    }

    private void btnViewRegister_Click(object sender, RoutedEventArgs e)
    {
        DocumentRegisterWindow win = new DocumentRegisterWindow();
        win.ShowDialog();

        if (win.SelectedDrawing != null)
        {
            Attachment.DwgNo = win.SelectedDrawing.DwgNo;
            Attachment.DwgTitle = win.SelectedDrawing.Title;
        }
    }
}

和xaml:

<UserControl x:Class="DrawingInsertControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="310" d:DesignWidth="800" >
<Border BorderBrush="Black" BorderThickness="2" Margin="10">
    <Grid>

...

<TextBox Grid.Column="1" Name="txtDocNo" Text="{Binding DwgNo}" />

最后是附加对象,它位于一个单独的模块中:

Public Class MailAttachment
    Public Property DwgNo As String
End Class

我省略了名称空间和其他我认为不相关的东西。 提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您的MailAttachment班级应实施INotifyPropertyChanged接口:

public class MailAttachment: INotifyPropertyChanged
{

    private string dwgNo;
    public string DwgNo{
        get { return dwgNo; }
        set
        {
            dwgNo=value;
            // Call NotifyPropertyChanged when the property is updated
            NotifyPropertyChanged("DwgNo");
        }
    }

  // Declare the PropertyChanged event
  public event PropertyChangedEventHandler PropertyChanged;

  // NotifyPropertyChanged will raise the PropertyChanged event passing the
  // source property that is being updated.
  public void NotifyPropertyChanged(string propertyName)
  {
     if (PropertyChanged != null)
     {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
     }
  }  
}

这会强制您的控件观察PropertyChanged事件。因此,您可以通知您的控件有关更改。

我提供的代码是在C#上,但是,我希望你能将它翻译成VB.Net。