我有一个可重复使用的UserControl,用于使用带有DependencyProperty SelectedCulture的combobox选择语言。然后,我使用包含UserViewModel集合的UsersViewModel,在DataGrid中显示另一个控件,其中包含用户列表。一列是包含语言选择控件的DataGridTemplateColumn。我将属性SelectedCulture绑定到UserViewModel的属性,但绑定不更新UserViewModel的值,除非UpdateSourceTrigger设置为PropertyChanged。
为什么不呢?不应该是PropertyChanged的默认值?
LanguageSelectView:
<UserControl x:Class="MyControls.LanguageSelectView" ... >
...
<ComboBox
ItemsSource="{Binding ViewModel.AvailableCultures, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:LanguageSelectView}}}"
SelectedItem="{Binding SelectedCulture, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:LanguageSelectView}}}"
>
<ComboBox.ItemTemplate>
...
</ComboBox.ItemTemplate>
</ComboBox>
</UserControl>
代码背后的代码:
public static readonly DependencyProperty SelectedCultureProperty = DependencyProperty.Register(nameof(SelectedCulture), typeof(CultureInfo),
typeof(LanguageSelectView), new FrameworkPropertyMetadata(null) {BindsTwoWayByDefault = true, DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged});
public CultureInfo SelectedCulture
{
get { return (CultureInfo) GetValue(SelectedCultureProperty); }
set { SetValue(SelectedCultureProperty, value); }
}
[Import]
public LanguageSelectViewModel ViewModel { get; set; }
UsersView:
...
<DataGrid ItemsSource="{Binding Users}" AutoGenerateColumns="False" Name="DataGrid" SelectionChanged="DataGrid_OnSelectionChanged">
<DataGrid.Columns>
<DataGridTemplateColumn Header="{wpf:Localize PrefferedLanguage}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<localization:LanguageSelectView SelectedCulture="{Binding SelectedCulture}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
...
UserViewModel:
public class UserViewModel
{
...
public CultureInfo SelectedCulture
{
get { <Getter> }
set { <Setter> <-- It's not getting called! }
}
}
当我使用UpdateSourceTrigger = PropertyChanged更新绑定时,一切都按预期工作。我检查了是否使用PropertyChangedCallback通过语言控件更新了DependencyProperty并且它没有问题,因此看起来像绑定在UsersView一侧的问题。
谢谢!