2

我正在努力寻找解决绑定问题的方法。

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

这是后面的精简代码:

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

和xml:

<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

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

4

1 回答 1

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。

于 2013-01-29T10:36:40.553 回答