This example demonstrates a file browser control that displays the path of the selected file in a text box and allows browsing files.
<UserControl ... x:Class="Test.UserControls.FileBrowserControl"> <Grid ...> <TextBox Text="{Binding SelectedFile}" /> </Grid> </UserControl>
public class FileBrowserControl : UserControl { public ICommand BrowseCommand { get; set; } public static DependencyProperty SelectedFileProperty = DependencyProperty.Register("SelectedFile", ...); public string SelectedFile { get => (string)GetValue(SelectedFileProperty); set => SetValue(SelectedFileProperty, value); } public string Filter { get; set; } public FileBrowserControl() { ... this.DataContext = this; // 将 DataContext 设置为 FileBrowserControl 实例。 } private void Browse() { ... SelectedFile = dialog.FileName; // 更新 FileBrowserControl 实例的 SelectedFile 属性。 } }
<:> Question:
<FileBrowserControl Filter="XSLT File (*.xsl)|*.xsl|All Files (*.*)|*.*" SelectedFile="{Binding SelectedFile}" />
When clicking the "Browse" button, the text box in the file browser control will be updated correctly, but the SELECTEDFILE property of the parent control ViewModel will not be set.
<本> The root cause:
The problem is that the DataContext is set to itself in the constructor of FileBrowserControl to itself:
This conflict with the inheritance bound to the ViewModel, because it destroys any data binding attributes binding binding using RelativeSource.<决> Solution:
this.DataContext = this;
In order to solve this problem, the binding in the XAML of UserControl should be modified:
This can ensure that the SelectedFile property is bound to the SELECTEDFILE attribute in the parent control part, which inherits the DataContext of its father's control. By specifying
, the binding will find the parent level of UserControl up, so as to find the correctattribute.
<TextBox Text="{Binding SelectedFile, RelativeSource={RelativeSource AncestorType=UserControl}}" />
attributes of the parent ViewModel will be updated correctly. RelativeSource AncestorType=UserControl
The above is the detailed content of Why Doesn't My Parent ViewModel's `SelectedFile` Property Update When Using a DependencyProperty in a UserControl?. For more information, please follow other related articles on the PHP Chinese website!