UserControl属性绑定不更新DataContext

时间:2014-03-17 02:41:47

标签: c# wpf xaml user-controls

我创建了这个简单的可重用控件来浏览文件。

然后我做了一个模型并实现了OnPropertyChanged并在MainWindow中使用了控件。

当我单击UserControl中的“浏览”按钮时,DependencyProperty“FilePath”被正确设置(并且文本框获取路径字符串)但模型似乎不起作用。

其他信息:如果我使用普通文本框而不是UserControl广告

<TextBox Text="{Binding InputFile}"/>

当我在框中输入内容时,模型会正确更新。 如果我在UserControl中手动输入内容(而不是通过“浏览”按钮填充它,它无论如何都不起作用)

这是UserControl的代码,属性在控件中正确设置:

public partial class FileBrowserTextBox : UserControl
{
    public FileBrowserTextBox()
    {
        InitializeComponent();
    }

    // FilePath
    public static readonly DependencyProperty FilePathProperty =
        DependencyProperty.Register("FilePath", typeof(string), typeof(FileBrowserTextBox), new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(OnFilePathPropertyChanged)));

    public string FilePath
    {
        get { return (string)GetValue(FilePathProperty); }
        set { SetValue(FilePathProperty, value); }
    }
    static void OnFilePathPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var obj = o as FileBrowserTextBox;
        if (obj == null)
            return;
    }
    private void BrowseButton_Click(object sender, RoutedEventArgs e)
    {
        // Create OpenFileDialog 
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        // Set filter for file extension and default file extension 
        dlg.DefaultExt = ".txt";
        dlg.Filter = "TXT Files (*.txt)|*.txt|All Files (*.*)|*.*";
        // Display OpenFileDialog by calling ShowDialog method 
        Nullable<bool> result = dlg.ShowDialog();
        // Get the selected file name and display in a TextBox 
        if (result == true)
        {
            // Open document 
            string filename = dlg.FileName;
            FilePath = filename; // this works and updates the textbox
        }
    }
}

这是XAML的摘录:

<UserControl x:Class="DrumMapConverter.FileBrowserTextBox">
        ...
        <Button Content=" ... " Click="BrowseButton_Click"/>
        <TextBox Name="txtFilepath" Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=FilePath}"/>
        ...
</UserControl>

这是我使用INotifyPropertyChanged的模型:

public class DrumMapConverterDataModel :INotifyPropertyChanged
{
    public string InputFile
    {
        get { return inputFile; }
        set
        {
            inputFile = value;
            OnPropertyChanged("InputFile");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    // Create the OnPropertyChanged method to raise the event 
    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

    private string inputFile;
}

这是MainWindow类

public partial class MainWindow : Window
{
    private DrumMapConverterDataModel model;
    public MainWindow()
    {
        InitializeComponent();
        model = new DrumMapConverterDataModel();
        DataContext = model;
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(model.InputFile); // if i break here the model has no data changed (InputFile is null)
    }
}

这就是我使用2个控件的方式(2个例子都不起作用):

<cust:FileBrowserTextBox  Label="Input File" FilePath="{Binding InputFile}"/>
<cust:FileBrowserTextBox  Label="Input File" FilePath="{Binding Path=InputFile, Mode=TwoWay, 
                       RelativeSource={RelativeSource FindAncestor, 
                           AncestorType=Window}}"/>

任何帮助都会非常感激。

更新和解决方案:

根据@AnatoliyNikolaev的建议(感谢他对UpdareSourceTrigger的解释)和用户控件中的@Karuppasamy,可以这样做(明确使用 UpdateSourceTrigger ,因为它是一个文本框):

<TextBox Grid.Column="2" Name="txtFilepath" Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=FilePath, UpdateSourceTrigger=PropertyChanged}"/>

然后DependencyProperty可以是这样的(注意 BindsTwoWayByDefault ):

public static readonly DependencyProperty FilePathProperty =
    DependencyProperty.Register("FilePath", typeof(string), typeof(FileBrowserTextBox), new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(OnFilePathPropertyChanged)) { BindsTwoWayByDefault = true });

所以最后在MainWindow我可以简单地写一下:

<cust:FileBrowserTextBox  FilePath="{Binding Path=InputFile}" />

2 个答案:

答案 0 :(得分:3)

尝试将依赖项属性集UpdateSourceTrigger设置为PropertyChanged

  

默认值为 Default ,它返回目标依赖项属性的默认UpdateSourceTrigger值。但是,大多数依赖项属性的默认值为PropertyChanged,而Text属性的默认值为LostFocus

示例:

<local:FileBrowserTextBox FilePath="{Binding Path=InputFile, 
                                             Mode=TwoWay,
                                             UpdateSourceTrigger=PropertyChanged}" />

答案 1 :(得分:2)

希望我理解你的问题,

我尝试了相同的操作,并在将UserControl的XAML代码中的TextBox绑定时将UpdateSourceTrigger设置为PropertyChanged。以下是我的代码,

 <TextBox Width="200" Name="txtFilepath" Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=FilePath, UpdateSourceTrigger=PropertyChanged}"/>
    <Button Width="40" Content=" ... " Click="BrowseButton_Click"/>

它正在发挥作用。

由于