UserControl属性绑定没有更新DataContext

本文关键字:更新 DataContext 属性 绑定 UserControl | 更新日期: 2023-09-27 17:50:44

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

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

当我单击UserControl中的Browse按钮时,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 });

所以最后在主窗口中我可以简单地这样写:

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

UserControl属性绑定没有更新DataContext

尝试将您的依赖属性设置为UpdateSourceTriggerPropertyChanged:

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

的例子:

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

希望我理解你的问题,

我也尝试过,并将UpdateSourceTrigger设置为PropertyChanged,同时在UserControl的XAML代码中绑定TextBox。下面是我的代码

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

它正在工作。

谢谢