我在 CellTemplate 中为 ListView 内的 ListViewItem 中的一行定义了一个 DataTrigger ...如何让它选择它所属的整个行?
问问题
231 次
2 回答
2
您不应该在DataTrigger
. 在您的视图模型中选择它:
a) 定义IsSelected
属性并更改此属性值,当DataTrigger
基于的条件变为真时:
public class DiabloIICharacter : ViewModelBase
{
public String Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
OnPropertyChanged("Name");
}
}
}
private String name;
public Boolean IsBoss
{
get { return isBoss; }
set
{
if (isBoss != value)
{
isBoss = value;
OnPropertyChanged("IsBoss");
if (isBoss)
// when a character becomes a boss, it becomes selected too
IsSelected = true;
}
}
}
private Boolean isBoss;
public Boolean IsSelected
{
get { return isSelected; }
set
{
if (isSelected != value)
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
private Boolean isSelected;
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new[]
{
new DiabloIICharacter { Name = "Diablo", IsBoss = true },
new DiabloIICharacter { Name = "Oblivion Knight", IsBoss = false },
new DiabloIICharacter { Name = "Blood Lord", IsBoss = false },
new DiabloIICharacter { Name = "Andariel", IsBoss = true },
new DiabloIICharacter { Name = "Baal", IsBoss = true },
new DiabloIICharacter { Name = "Minion of Destruction", IsBoss = false },
new DiabloIICharacter { Name = "Megademon", IsBoss = false },
};
}
}
b) 绑定ListViewItem.IsSelected
和ViewModel.IsSelected
通过ItemContainerStyle
:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
SizeToContent="WidthAndHeight">
<Grid>
<ListView ItemsSource="{Binding}">
<ListView.Resources>
<DataTemplate x:Key="IsBossTemplate">
<Rectangle Fill="Red" Width="50" Height="20" x:Name="IsBossMark"/>
<DataTemplate.Triggers>
<DataTrigger Value="True" Binding="{Binding IsBoss}">
<Setter TargetName="IsBossMark" Property="Fill" Value="DarkRed"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.Resources>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Character name"
DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Is boss"
CellTemplate="{StaticResource IsBossTemplate}"/>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
于 2012-08-22T07:58:40.513 回答
1
只需将名称应用于 ListView。就像<ListView Name="mylistView"... />
现在你可以像这样在你的单元格模板中创建一个绑定,
{Binding SelectedItem, ElementName=mylistView}
你就可以绑定到选定的项目
于 2012-08-22T08:06:23.597 回答