【发布时间】:2014-05-17 04:47:14
【问题描述】:
所以我在我的视图模型中定义了许多项目,然后我想将它们添加到我在 XAML 中的视图中。由于这些项目很多,我试图通过创建为视图模型中的自定义类定义的数据模板来减少一些冗余,然后将它们嵌套在 XAML 中。到目前为止,我所拥有的看起来像这样。
<Page.Resources>
<DataTemplate x:Name="CommandCenterTemplate" >
<Grid d:DataContext="{d:DesignInstance core:ComboBoxCommandCenter}">
<Grid.RowDefinitions >
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Button Width="150" Content="{Binding Title}" Command="{Binding OnClickCommand}"/>
<ComboBox Grid.Column="1" ItemsSource="{Binding Options}" SelectedValue="{Binding Selected,Mode=TwoWay}"/>
</Grid>
</DataTemplate>
<!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
<x:String x:Key="AppName">Combat</x:String>
</Page.Resources>
之前在 XAML 内联中逐项列出了这些内容,如下所示:
<StackPanel Orientation ="Horizontal">
<Button Width="150" Content="Skills" Command="{Binding SkillCommand}"></Button>
<ComboBox ItemsSource="{Binding SkillOptions}" SelectedValue="{Binding SkillSelected,Mode=TwoWay}"></ComboBox>
</StackPanel>
View-Model 中定义的类如下所示:
public class ComboBoxCommandCenter : INotifyPropertyChanged
{
private IEnumerable<string> _options;
private string _title;
public ComboBoxCommandCenter(string title,IEnumerable<string> options, Action<string> action)
{
_options = options;
OnClickAction = action;
}
private Action<string> OnClickAction { get; set; }
public string Selected { get; set; }
public IEnumerable<string> Options
{
get { return _options; }
}
public ICommand OnClickCommand
{
get { return new MvxCommand(() => OnClickAction(Selected)); }
}
public string Title
{
get { return _title; }
set
{
_title = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
所以我希望能够用已经实例化的视图模型中的类的实例替换堆栈面板对象。
public class CombatViewModel : BaseViewModel
{
public ComboBoxCommandCenter SaveCenter { get; private set; }
public CombatViewModel(ICharacterService 角色) :基础(字符) { SaveCenter = new ComboBoxCommandCenter("Save",MyCharacter.Actions.SaveOptions(), MyCharacter.Actions.Save); } }
那么有没有办法在 XAML 中放置一些代码,使其看起来像
<core:ViewModel.SaveCenter />
【问题讨论】:
标签: xaml windows-runtime mvvmcross