【问题标题】:Template selector and creation of ViewModel模板选择器和 ViewModel 的创建
【发布时间】:2012-02-22 10:20:57
【问题描述】:

我有一个带有 ItemTemplateSelector 的 ItemsControl,对于某些模板,我需要创建一个带有参数的 ViewModel(如果需要,我可以使用 ViewModelLocator)。我该怎么做 ?使用转换器是唯一的方法吗?

<DataTemplate x:Key="DataGridTemplate">
        <Control:MyView DataContext="???CreateViewModelWithParameter" />
    </DataTemplate>

【问题讨论】:

    标签: c# .net wpf mvvm mvvm-light


    【解决方案1】:

    使用 ObjectDataProvider,然后绑定 Data Context。

    为清楚起见,下面的示例是针对按钮进行的​​。对您的按钮控件执行相同操作。您最终会得到一个窗口和一个带有文本“Joe”的按钮。

    查看模型:

    public class MyVM
    {
        public string name { get; set; }
        public MyVm( string n ) {
            name = n;
        }
    }
    

    查看:

    <Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:clr="clr-namespace:System;assembly=mscorlib"
        xmlns:so="clr-namespace:SO"
        Width="300" Height="200"
        x:Class="SO.MainWindow"
        Title="SO Sample"
        >
        <Window.Resources>
            <ObjectDataProvider x:Key="datasrc" ObjectType="{x:Type so:MyVm}">
                <ObjectDataProvider.ConstructorParameters>
                    <clr:String>Joe</clr:String>
                </ObjectDataProvider.ConstructorParameters>            
            </ObjectDataProvider>
        </Window.Resources>
        <Button DataContext="{Binding Source={StaticResource ResourceKey=datasrc}}" Content="{Binding Path=name}" />
    </Window>
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多