WPF Prism框架下如何用DependencyProperty关联ViewModel与UserControl属性
问题根因
你开启了prism:ViewModelLocator.AutoWireViewModel="True"后,ItemTest的DataContext会被Prism自动赋值为ItemTestViewModel实例,你在InputView中给ItemTest的Title依赖属性绑定的值,只会传递到ItemTest控件本身的属性,没有同步到ItemTestViewModel的TitleViewModel属性,因此TextBlock绑定TitleViewModel时拿不到值。
解决方案
方案一:直接修改XAML绑定(最简方案,适合仅展示场景)
如果Title值不需要在ViewModel中做业务逻辑处理,直接绑定控件自身的Title依赖属性即可,无需修改后台代码。把ItemTest的XAML中TextBlock的绑定修改为:
<TextBlock Grid.Row="1" Text="{Binding Title, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
方案二:依赖属性同步到ViewModel(适合需业务处理场景)
如果需要在ItemTestViewModel中使用Title值做逻辑处理,就给Title依赖属性添加变更回调,同步值到ViewModel。修改ItemTest后台代码:
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(ItemTest), // 新增属性变更回调 new PropertyMetadata(null, OnTitleChanged)); private static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is ItemTest itemTest && itemTest.DataContext is ItemTestViewModel vm) { vm.TitleViewModel = e.NewValue?.ToString(); } } public string Title { get => (string)GetValue(TitleProperty); set => SetValue(TitleProperty, value); }
注意事项
确认InputView中Title="{Binding title}"的绑定源:InputItems集合的每个项的title属性必须为public,如需动态更新该值,对应的类需要实现INotifyPropertyChanged接口。
内容的提问来源于stack exchange,提问作者fj mn
相关产品推荐
相关产品推荐

