0

我有这个数据模板:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Model="clr-namespace:Effectus.Model"
xmlns:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
>

<DataTemplate DataType="{x:Type Model:ToDoAction}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <TextBlock Text="Title" 
                   Grid.Row="0" Grid.Column="0"/>
        <TextBox Text="{Binding Path=Title}"
                   IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext.AllowEditing.Value}"
                   Grid.Row="0" Grid.Column="1"/>

        <TextBlock Text="Content" 
                   Grid.Row="1" Grid.Column="0"/>
        <TextBox Text="{Binding Path=Content}"
            IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext.AllowEditing.Value}"
            AcceptsReturn="True"
            MinHeight="100"
            Grid.Row="2" Grid.ColumnSpan="2"/>

        <TextBlock Text="Owner"
                   Grid.Row="6" Grid.Column="0"/>
        <ComboBox SelectedItem="{Binding Path=Owner}" DisplayMemberPath="Username" SelectedValuePath="Username"
                  ItemsSource="{Binding Converter={StaticResource EnumValuesConverter}, ConverterParameter={x:Type Model:Status}}"
                  IsEnabled="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext.AllowEditing.Value}"
                  Grid.Row="6" Grid.Column="1"/>

    </Grid>
</DataTemplate>

在最后一部分中,您可以看到一个 TextBlock,其 Text 为“Owner”,然后是一个 ComboBox。只是为了给您提供上下文,这是我目前正在开发的 ToDo 应用程序的一小部分(我正在尝试进入 MVVM)。我使用的 XAML 是 ToDoAction 对象的 DataTemplate。我希望所有用户都填写“所有者”组合框。我可以通过 NHibernate 从 DB 获取它们,但我对如何将 DataTemplate 绑定到我的 DataSource (在我的情况下是 Nhibernate Session,但我觉得这更普遍)没有最模糊的想法。请给点小建议好吗?非常感谢大家!

4

1 回答 1

1

有多种方法可以处理它,比如我从未使用过的ObjectDataProvider 。但我认为最简单和最快的方法是使用单例。

public sealed class UserList
{
    public ObservableCollection<User> Users {get; private set;}

    public static UserList Instance
    {
        get{return sInstance;}
    }

    private static UserList sInstance = new UserList();
}

您可以像往常一样更新和修改用户列表,并且必须绑定到此集合。

ItemsSource="{Binding Source={x:Static my:UserList.Instance}, Path=Users}
于 2012-11-28T12:07:17.230 回答