gpt4 book ai didi

c# - UserControl 属性绑定(bind)不更新 DataContext

转载 作者:行者123 更新时间:2023-11-30 14:30:34 24 4
gpt4 key购买 nike

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

然后我做了一个模型并实现了 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;
}

这是主窗口类

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}" />

最佳答案

尝试为您的依赖属性集 UpdateSourceTriggerPropertyChanged:

The default is Default, which returns the default UpdateSourceTrigger value of the target dependency property. However, the default value for most dependency properties is PropertyChanged, while the Text property has a default value of LostFocus.

例子:

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

关于c# - UserControl 属性绑定(bind)不更新 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22446054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com