【问题标题】:Wiring up inner ViewModels to UserControls in Silverlight在 Silverlight 中将内部 ViewModel 连接到 UserControl
【发布时间】:2010-08-10 12:50:15
【问题描述】:

我正在尝试显示笔记列表。我有一个绑定到 NoteViewModel 集合的 ItemsControl。所以在项目控件的数据模板中,我想创建一个 NoteControl(用于显示注释的用户控件)并将其 ViewModel 属性绑定到集合中的 NoteViewModel。

我目前有这个:

    <ItemsControl x:Name="itemsControl1" Grid.Row="1" ItemsSource="{Binding Notes}" >
        <ItemsControl.Template>
            <ControlTemplate TargetType="ItemsControl">
                <ScrollViewer>
                    <ItemsPresenter/>
                </ScrollViewer>
            </ControlTemplate>
        </ItemsControl.Template>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <uc:NoteControl uc:NoteControl.ViewModel="{Binding}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

但我遇到了这个异常:

System.ArgumentException: Object of type 'System.Windows.Data.Binding' cannot be converted to type 'NotePrototype.NoteViewModel'.

将其连接起来的正确语法是什么?是否有更好的技术将内部 ViewModel 连接到动态创建/绑定的内部 UserControl?

【问题讨论】:

    标签: silverlight silverlight-4.0


    【解决方案1】:

    最好将 ViewModel 附加到您的 UserControl 的 DataContext 中,并且在您不需要 ViewModel 属性的用户控件中,您可以绑定到隐式 Datacontext 因为那将是您的 ViewModel

    补充说明: 要在设计器中启用数据绑定,请遵循以下示例:

    <UserControl  
                <!--
                  all the other declaration needed are here
                -->
            xmlns:local="clr-namespace:NotePrototype"
            d:DataContext="{DynamicResource ViewModel}" 
    >
        <UserControl.Resources>
            <local:NoteViewModel x:Key="ViewModel" d:IsDataSource="True" />
        </UserControl.Resources>
    
    <!--
      put your content here
    -->
    </UserControl>
    

    编辑了 ItemsControl 的示例:

    <ItemsControl x:Name="itemsControl1" Grid.Row="1" ItemsSource="{Binding Notes}" >
        <ItemsControl.Template>
            <ControlTemplate TargetType="ItemsControl">
                <ScrollViewer>
                    <ItemsPresenter/>
                </ScrollViewer>
            </ControlTemplate>
        </ItemsControl.Template>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <uc:NoteControl DataContext="{Binding}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    【讨论】:

    • 恐怕我不明白。 XAML 在我的 ItemsControl 的 ItemTemplate 中会是什么样子?
    • 谢谢!现在这是有道理的。 :-)
    猜你喜欢
    • 1970-01-01
    • 2011-10-02
    • 2013-10-07
    • 2011-04-09
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 2013-07-02
    相关资源
    最近更新 更多