WPF和Caliburn.Micro的曲线相对较低。
我的目标是将组合框选定项目的绑定从后面的ShellView代码移动到视图模型,就像组合框的项目集合一样。
XAML :
<Window x:Class="EomDatabaseUtility.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Eom Tool Database Utility" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="258" HorizontalAlignment="Left" Margin="12,41,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479" />
<Button Content="Execute" Height="23" HorizontalAlignment="Left" Margin="416,12,0,0" VerticalAlignment="Top" Width="75" x:Name="Execute" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top" Width="120" x:Name="CatalogName" SelectedValuePath="{Binding Path=SelectedCatalogName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
代码隐藏(目标是不必添加任何代码,如果我理解正确的话):
namespace EomDatabaseUtility.Views
{
using System.Windows;
public partial class ShellView : Window
{
public ShellView()
{
InitializeComponent();
}
// --> This should go in the view model, Right?
private string selectedCatalogName;
public string SelectedCatalogName
{
get { return selectedCatalogName; }
set { selectedCatalogName = value; }
}
}
}
查看模型(目前向组合框提供项目集合以及按钮事件处理程序):
namespace EomDatabaseUtility.ViewModels
{
using Caliburn.Micro;
using System.Collections.Generic;
public class ShellViewModel : PropertyChangedBase
{
public List<string> CatalogName
{
get
{
return new List<string> { "foo", "bar" };
}
}
public void Execute()
{
System.Windows.MessageBox.Show("hello");
}
}
}
答案 0 :(得分:35)
您可以将SelectedItem
的{{1}}绑定到视图模型上的属性:
ComboBox
事实上,由于您的<ComboBox x:Name="CatalogName" ... SelectedItem="{Binding SelectedCatalog}" />
public class ShellViewModel : PropertyChangedBase
{
private string selectedCatalog;
public List<string> CatalogName
{
get
{
return new List<string> { "foo", "bar" };
}
}
public string SelectedCatalog
{
get
{
return this.selectedCatalog;
}
set
{
this.selectedCatalog = value;
this.NotifyOfPropertyChange(() => this.SelectedCatalog);
}
}
名称为 CatalogName ,因此Caliburn.Micro约定将查找名为ComboBox
(或SelectedCatalogName
)的属性并自动将ActiveCatalogName
的{{1}}绑定到该ComboBox
,因此您可以使用:
SelectedItem
有几点需要注意:
<ComboBox x:Name="CatalogName" ... />
public string SelectedCatalogName
{
...
}
的设置器中调用NotifyOfPropertyChange()
。每当我们从视图模型设置值时,这都会通知UI该值已更改,以便更新UI。此方法是SelectedCatalog
。PropertyChangedBase
或Caliburn.Micro的ObservableCollection
(实现Caliburn.Micro的{{1} }})。这允许在从视图模型中添加/删除集合中的对象时通知UI。BindableCollection
或IObservableCollection
类型(而不是Screen
),如果它将具有生命周期(激活/停用等),或者去有一个当前活动的项目(屏幕),可以在运行时更改。