gpt4 book ai didi

wpf - 如何为 Prism WPF设置用户控件的数据上下文?

转载 作者:行者123 更新时间:2023-12-03 10:26:23 25 4
gpt4 key购买 nike

这是我的 view.xaml :

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=".5*"/>
<RowDefinition Height="0.5*"/>
</Grid.RowDefinitions>

<Grid Grid.Row="0" x:Name="grdFormSearch" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<local:StudentUserControl HorizontalAlignment="Stretch" Height="100" VerticalAlignment="Stretch"/>
</Grid>
</Grid>

在上面,我在view.xaml中添加了 StudentUserControl

StudentUserControl.xaml.cs:
public partial class StudentUserControl : UserControl
{
public StudentUserControl(StudentViewModel ViewModel)
{
InitializeComponent();
this.DataContext = ViewModel;
}
}

StudentViewModel.cs:
public StudentViewModel(IEventAggregator eventAggregator, IUnityContainer container)
{
_eventAggregator = eventAggregator;
_container = container;
}

它在xaml中引发错误,因为它期望一个无参数的构造函数!

如何设置 DataContextUserControl
最好的方法是什么?

最佳答案

从 View 的构造函数中删除参数:

public partial class StudentUserControl : UserControl
{
public StudentUserControl()
{
InitializeComponent();
}
}

如果您希望能够像在此处那样在XAML标记中创建 View 的实例,则它不应该存在:
<local:StudentUserControl HorizontalAlignment="Stretch" Height="100" VerticalAlignment="Stretch"/>

此外,无论如何,您都不应在背后的代码中显式设置 View 的 DataContext。在大多数情况下, DataContext应该从父元素(即您的案例)中的view.xaml继承,并且如果您在 View 的构造函数中显式设置DataContext,则会破坏继承。

如果由于某种原因父 View 没有 DataContext,则可以使用Prism的 View 模型定位器来创建 View 模型:
<UserControl x:Class="WpfApplication1.StudentUserControl"
...
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">

请引用以下链接以获取有关此的更多信息: http://brianlagunas.com/getting-started-prisms-new-viewmodellocator/

关于wpf - 如何为 Prism WPF设置用户控件的数据上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490038/

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