【发布时间】:2019-09-19 07:48:45
【问题描述】:
我有以下 xaml 视图:
<UserControl x:Class="MyViews.PersonView"
xmlns:views="clr-namespace:MyViews"
[...]
>
[...]
<dxb:BarManager x:Name="MainBarManager">
<dxb:BarManager.Items>
<dxb:BarButtonItem x:Name="bbiPrint"
Content="{Binding Print, Source={StaticResource CommonResources}}"
Command="{Binding PrintPersonsCommand}"
CommandParameter="{Binding PersonsCardView, ElementName=CardUserControl}"
/>
</dxb:BarManager.Items>
<Grid>
<Grid.RowDefinitions>
[...]
</Grid.RowDefinitions>
<views:CardView x:Name="CardUserControl" Grid.Row="2"/>
</Grid>
[...]
</UserControl>
CardView 定义如下:
<UserControl x:Class="MyViews.CardView"
[...]>
[...]
<dxg:GridControl ItemsSource="{Binding Persons}" SelectedItems="{Binding SelectedPersons}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" SelectionMode="MultipleRow">
[...]
<dxg:GridControl.View>
<dxg:CardView x:Name="PersonsCardView"
[...]
CardTemplate="{StaticResource DisplayCardTemplate}"
PrintCardViewItemTemplate="{StaticResource PrintCardTemplate}"/>
</dxg:GridControl.View>
[...]
</dxg:GridControl>
</UserControl>
PrintPersonsCommand 在我的 ViewModel 中定义如下:
public class PersonViewModel
{
public PersonViewModel(...)
{
[...]
PrintPersonsCommand = new Prism.Commands.DelegateCommand<DataViewBase>(PrintPersons, CanPrintPersons);
}
public Prism.Commands.DelegateCommand<DataViewBase> PrintPersonsCommand { get; private set; }
private void PrintPersons(DataViewBase view)
{
_printService.ShowGridViewPrintPreview(view);
}
private bool CanPrintPersons(DataViewBase view)
{
return true;
}
}
现在,当我单击“打印”按钮时,上面的PrintPersons 方法总是会输入null。如何在上面的MyViews.PersonView xaml 中传递CardUserControl.PersonsCardView,如何将PersonCardView 传递给我的命令?换句话说,我该如何解决
CommandParameter="{Binding PersonsCardView, ElementName=CardUserControl}"
让它工作?
目前,我发现解决此问题的唯一方法是将Command 和CommandParameter 替换为
ItemClick="OnPrintBtnClick"
然后在PersonView的代码隐藏文件中做:
private void OnPrintBtnClick(object sender, ItemClickEventArgs e)
{
var ctxt = DataContext as PersonViewModel;
ctxt.PrintPersonsCommand.Execute(CardUserControl.PersonsCardView);
}
这行得通,但我不敢相信没有其他方法。我对该解决方案不满意,因为我不再拥有使用Command 的好处,例如命令的CanExecute 方法的自动评估。我也可以将CardView 的xaml 代码放在PersonView.xaml 中,但我喜欢将我的控件放在单独的文件中,因为我觉得它更有条理,而且每个用户控件都有自己的职责,可以很好地拆分为单独的文件文件。此外,该解决方案将我的视图绑定到我的视图模型过于紧密。
有人可以帮帮我吗?
【问题讨论】:
-
你需要这个参数做什么? IE。
PersonsCardView中有什么,PersonViewModel中没有? -
我想打印我的卡片视图的卡片。我有其他视图,例如网格视图。
PersonViewModel没有关于PersonsCardView的信息。它只带有打印视图所需的逻辑。我不希望PersonViewModel有任何关于要打印的视图的信息。它会将视图模型与视图绑定得太紧。 -
我的
PersonView的子视图(如上面提到的CardView和上面没有提到的GridView)都共享相同的视图模型。 -
公平点,但是将视图作为参数传递给视图模型看起来已经是我能想象的最紧密的耦合了。
-
不,因为我传递了它的抽象。
CardView和GridView都继承自DataViewBase。我不希望我的应用中使用的任何视图属于不同类型。