我正在尝试禁用用户对列表视图中行的选择,但我仍然希望该行上的任何按钮都可以单击。到目前为止,我已在列表视图上使用eventSetter来将事件PreviewLeftMouseDown设置为一个除了以下操作外不执行任何操作的函数:
e.handled = true;
但这也使我在该行中具有的按钮不可单击。是否有一个选项可以覆盖事件PreviewLeftMouseDown,以便该按钮可以单击,或者完全以其他方式进行单击?
我仍然希望通过代码突出显示某些行,就像用户选择它们一样。
谢谢!
答案 0 :(得分:1)
我用INotifyPropertyChanged
创建了一个名为 Data 的类。
public class Data : INotifyPropertyChanged
{
public string Text { get; set; }
private string selectedBackGround;
public string SelectedBackGround
{
get
{
return selectedBackGround;
}
set
{
selectedBackGround = value;
NotifyPropertyChanged("SelectedBackGround");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
在Xaml中,我使用 SelectedBackGround 属性覆盖了ControlTemplate并绑定到StackPanel
Background。此属性 SelectedBackGround 仅用于通过代码更改颜色。
<ListView x:Name="ListView1" SelectionChanged="ListView_SelectionChanged" HorizontalAlignment="Left" Height="135.924" Margin="194.529,104.462,0,0" VerticalAlignment="Top" Width="302.311" ItemsSource="{Binding ListOfstring}" >
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal" Background="{Binding SelectedBackGround}">
<TextBlock Text="{Binding Text,UpdateSourceTrigger=Explicit}" Foreground="Black"/>
<Button x:Name="btn1" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Btn1_Click_1" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
</ListView.ItemContainerStyle>
</ListView >
这就是我填写收藏集的方式。
public MainWindow()
{
ListOfstring = new ObservableCollection<Data>();
InitializeComponent();
ListOfstring.Add( new Data{ Text="TEST1", SelectedBackGround = "White" });
ListOfstring.Add( new Data{ Text="TEST2", SelectedBackGround = "White" });
ListOfstring.Add( new Data{ Text="TEST3", SelectedBackGround = "White" });
ListOfstring.Add( new Data{ Text = "TEST4", SelectedBackGround = "White" });
this.DataContext = this;
}
如您所见,按钮已订阅了click事件。
private void Btn1_Click_1(object sender, RoutedEventArgs e)
{
// Whenever you click on the any list item button, you are changing background
// of the 3rd item in the list view to Aqua Color.
ListOfstring[2].SelectedBackGround = "Aqua";
}