我在WPF中有一个简单的用户控件,它包含一些按钮,文本框和列表视图。我简化了一点控制:
<UserControl x:Class="Example.SearchListControl"
...
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" />
<ListView Grid.Row="1" ItemsSource="{Binding Items}" SelectedItem="{Binding Current}" />
<Button Grid.Row="2" Command="{Binding SomeSortOfCommand}">
</Grid>
</UserControl>
该usercontrol的ViewModel如下所示:
public class SearchListViewModel<T> : ViewModelBase
{
private ObservableCollection<T> _items;
public ObservableCollection<T> Items
{
get
{
return _items;
}
set
{
_items = value;
OnPropertyChanged();
}
}
private T _current;
public T Current
{
get
{
return _current;
}
set
{
_current = value;
OnPropertyChanged();
}
}
...
}
我把那个控件放在另一个窗口中:
<Window x:Class="Example.TestWindow"
...>
<Grid>
<local:SearchListControl DataContext="{Binding GenericSearchListViewModel}" />
</Grid>
</Window>
为了获得更大的灵活性,我想从窗口中为该控件中的ListView设置datatemplate?类似的东西:
<Window ...>
<Window.Resources>
<DataTemplate x:Key="ListViewTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=ShortCaption}" />
<TextBlock Grid.Column="1" Text="{Binding Path=Caption}" />
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<local:SearchListControl DataContext="{Binding GenericSearchListViewModel}"
DataTemplate="{StaticResource ListViewTemplate}" />
</Grid>
</Window>
这是可能的,还是我完全错误的方式?
答案 0 :(得分:0)
如果您在SearchListUserControl.xaml文件中为ListView提供名称:
<ListView x:Name="lv" ... />
...您可以通过SearchListControl类的属性轻松公开其ItemTemplate属性:
public abstract class SearchListControl : UserControl
{
public SearchListControl()
{
InitializeComponent();
}
public DataTemplate DataTemplate
{
get { return lv.ItemTemplate; }
set { lv.ItemTemplate = value; }
}
}
...并从窗口设置:
<local:SearchListControl DataContext="{Binding GenericSearchListViewModel}"
DataTemplate="{StaticResource ListViewTemplate}" /