【发布时间】:2013-03-12 18:56:20
【问题描述】:
有没有办法通过 Caliburn.Micro 重用 WPF 视图?
在示例中,我有一个带有 SaveAndClose 和 Cancel 按钮的 DetailViewBase.xaml。现在我想在 PersonView(Model) 中使用 DetailViewModelBase 和 XAML。
我希望这个问题很清楚。
【问题讨论】:
标签: wpf caliburn.micro
有没有办法通过 Caliburn.Micro 重用 WPF 视图?
在示例中,我有一个带有 SaveAndClose 和 Cancel 按钮的 DetailViewBase.xaml。现在我想在 PersonView(Model) 中使用 DetailViewModelBase 和 XAML。
我希望这个问题很清楚。
【问题讨论】:
标签: wpf caliburn.micro
如果我的假设是正确的,我认为您的意思是您想从几个更简单的视图模型中“组合”一个更复杂的视图。您可以从视图模型继承,但显然视图模型一次只能有一个活动视图。
但是,使用绑定,您可以组合多个视图模型,并让它们全部一起呈现各自的视图,以制作更复杂的 UI
例如
带有保存/取消按钮的虚拟机
public class ActionsViewModel
{
public void Save()
{
}
public void Cancel()
{
}
}
对应的视图:
<UserControl>
<StackPanel Orientation="Horizontal">
<Button x:Name="Save">Save</Button>
<Button x:Name="Cancel">Cancel</Button>
</StackPanel>
</UserControl>
另一个视图组成自己和ActionsViewModel
public class ComposedViewModel
{
public ActionsViewModel ActionsView
{
get; set;
}
public ComposedViewModel()
{
ActionsView = new ActionsViewModel();
}
public void DoSomething()
{
}
}
观点:
<UserControl>
<StackPanel Orientation="Horizontal">
<TextBlock>Hello World</TextBlock>
<Button x:Name="DoSomething">Do Something</Button>
<ContentControl x:Name="ActionsView" />
</StackPanel>
</UserControl>
当您使用约定绑定(或使用附加属性)绑定ContentControl 时,CM 会自动将VM 绑定到DataContext 并连接视图。通过这种方式,您可以将多个虚拟机组合成一个更复杂的功能。
此外,由于操作消息冒泡 - 如果您要删除 ActionsViewModel 上的“确定”和“取消”实现并将它们放入 ComposedViewModel 实现中,操作消息将冒泡到 @ 987654330@ 实例并在那里触发方法
例如
public class ActionsViewModel
{
// Remove the command handlers
}
public class ComposedViewModel
{
public ActionsViewModel ActionsView
{
get; set;
}
public ComposedViewModel()
{
ActionsView = new ActionsViewModel();
}
public void DoSomething()
{
}
// CM will bubble the messages up so that these methods handle them when the user clicks on the buttons in the ActionsView
public void Save()
{
}
public void Cancel()
{
}
}
编辑:
抱歉,我忘记了这一点 - 基于约定的绑定不允许消息冒泡,但您只需使用 Message.Attach 附加属性即可:
// Make sure you include the caliburn namespace:
<UserControl xmlns:cal="http://www.caliburnproject.org">
<StackPanel Orientation="Horizontal">
<Button x:Name="Save" cal:Message.Attach="Save">Save</Button>
<Button x:Name="Cancel" cal:Message.Attach="Cancel">Cancel</Button>
</StackPanel>
</UserControl>
【讨论】:
您可以使用如下代码将 ViewModel 显式绑定到 View:
cal:Bind.Model={Binding DetailViewModelBase}
【讨论】: