1 回答

TA贡献1871条经验 获得超8个赞
在列表框中使用该单击处理程序会加剧您的问题。我不知道你是怎么做到的,但这不能只是点击。这可能是 previewmousedown。因为,当然,作为选择项目的一部分,列表框会“吃掉”鼠标按下。
解决此问题的一种方法是不使用该列表框预览鼠标。在这里,我将我的行内容放在一个按钮中并绑定按钮的命令。当然,它看起来不像一个按钮。
我把圆圈做成一个按钮,并给它一个透明的填充,这样你就可以点击所有的按钮。
<ListBox ItemsSource="{Binding People}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Command="{Binding DataContext.ItemClickCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
CommandParameter="{Binding}"
>
<Button.Template>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding LastName}"/>
<Button Command="{Binding DataContext.EllipseCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
>
<Button.Template>
<ControlTemplate>
<Ellipse Name = "TheEllipse" Stroke="Black"
Fill="Transparent"
Height ="12"
Width="12" Cursor="Hand">
</Ellipse>
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的视图模型使用中继命令,但(显然)任何 ICommand 的实现都可以。我有上一个问题的人,我做了一些工作。
public class MainWindowViewModel : BaseViewModel
{
private RelayCommand ellipseCommand;
public RelayCommand EllipseCommand
{
get
{
return ellipseCommand
?? (ellipseCommand = new RelayCommand(
() =>
{
Console.WriteLine("CIRCLE clicked");
}
));
}
}
private RelayCommand<Person> itemClickCommand;
public RelayCommand<Person> ItemClickCommand
{
get
{
return itemClickCommand
?? (itemClickCommand = new RelayCommand<Person>(
(person) =>
{
Console.WriteLine($"You clicked {person.LastName}");
person.IsSelected = true;
}
));
}
}
private ObservableCollection<Person> people = new ObservableCollection<Person>();
public ObservableCollection<Person> People
{
get { return people; }
set { people = value; }
}
public ListCollectionView LCV { get; set; }
public MainWindowViewModel()
{
People.Add(new Person { FirstName = "Chesney", LastName = "Brown" });
People.Add(new Person { FirstName = "Gary", LastName = "Windass" });
People.Add(new Person { FirstName = "Liz", LastName = "McDonald" });
People.Add(new Person { FirstName = "Carla", LastName = "Connor" });
}
}
当你点击那个外部按钮时,它会抓住点击。这就是为什么我在命令中设置 IsSelected 以便通过绑定选择您单击的项目。
- 1 回答
- 0 关注
- 103 浏览
添加回答
举报