【问题标题】:I want to bind a class' properties to controls in my user control我想将一个类的属性绑定到我的用户控件中的控件
【发布时间】:2013-01-12 21:32:20
【问题描述】:

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

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

这是一个精简的代码:

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

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

【问题讨论】:

    标签: c# wpf binding wpf-controls


    【解决方案1】:

    你的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。

    【讨论】:

    • Epic 兄弟,感谢您快速简洁的回复,完美运行!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多