将dataTemplate绑定到外部数据源

时间:2012-11-28 11:51:31

标签: wpf xaml nhibernate data-binding

我有这个DataTemplate:

<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为&#34; Owner&#34;,后跟ComboBox。 只是为了给你上下文,这是我目前正在研究的ToDo应用程序的一小部分(我试图进入MVVM)。 封装的XAML是ToDoAction对象的DataTemplate。 我想要&#34;所有者&#34; ComboBox由所有用户填写。我可以通过NHibernate从DB获取它们,但我对如何将DataTemplate绑定到我的DataSource(在我的情况下是一个Nhibernate Session,但我觉得这更通用)没有最微妙的想法。 你能给一些小建议吗? 非常感谢你们!

1 个答案:

答案 0 :(得分: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}
相关问题