[英]Hiding A Listbox Item in WPF
我有一個ListBox控件,其中填充了幾個ListBox項。 每個項目都包含一個“繼續”按鈕和一個“推遲”按鈕。 單擊“推遲”按鈕后,我想隱藏該ListBox項(在本例中顯示為一行)。 我目前擁有的代碼似乎沒有任何效果。
XAML:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding PostponeClicked}" Value="1">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
C#:
private void PostponeThirdPartyUpdatesButton_Click(object sender, RoutedEventArgs e)
{
DataTrigger d = new DataTrigger();
d.Binding = new Binding("PostponeClicked");
d.Value = 1;
var context = ((FrameworkElement)sender).DataContext as Tuple<RegScan_ThirdParty.InstalledApplicationFromRegistryScan, RegScan_ThirdParty.ManifestRequiredApplication, RegScan_ThirdParty.RequiredApplicationState>;
Button ThirdPartyPostponeButton = sender as Button;
ThirdPartyPostponeButton.IsEnabled = false;
if (context != null)
{
RegScan_ThirdParty.registryApplicationPostponeWorkflow(context);
}
ThirdPartyPostponeButton.IsEnabled = true;
}
我不得不處理同一件事。 列表框中的每個項目都應該是一個對象。 我們現在將其稱為MyObject
,因為我不知道您的對象類型是什么。 在MyObject類中,您將放入Proceed和Postpone命令。
//ViewModelBase implements INotifyPropertyChanged, which allows us to call RaisePropertyChanged, and have the UI update
class MyObject : ViewModelBase
{
private bool isNotPostponed = true;
public bool IsNotPostponed
{
get { return isNotPostponed; }
set
{
isNotPostponed = value;
RaisePropertyChanged("IsNotPostponed");
}
}
private Command postponeCommand;
public Command PostponeCommand
{
get
{
if (postponeCommand == null)
postponeCommand = new Command(PostponeCommand);
return postponeCommand;
}
}
private void Postpone(object x)
{
IsNotPostponed = false;
}
//similar code for Proceed Command
}
然后在顯示列表框的視圖的視圖模型中,創建一個可以綁定到列表框(或要使用的任何集合)的列表。 我在下面的XAML中將其稱為MyObjectsList。 (我沒有顯示該對象所在的ViewModel代碼,但我假設您具有綁定到ListBox的代碼。)然后在ItemsControl.ItemTemplate中,綁定到List中的每個MyObject。
<ItemsControl ItemsSource="{Binding MyObjectsList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<BooleanToVisibilityConverter x:Key="boolToVis"/>
</DataTemplate.Resources>
<StackPanel Visibility="{Binding IsNotPostponed, Converter={StaticResource boolToVis}}">
<Button Command="{Binding PostponeCommand}" Content="Postpone"/>
<Button Command="{Binding ProceedCommand}" Content="Proceed"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
單擊Postpone時,該命令將執行Postpone(),它將IsNotPostponed設置為false。 將IsNotPostponed設置為false時,RaisePropertyChanged告知UI IsNotPostponed已更改(您需要實現INotifyPropertyChanged接口。)最后,當UI獲取更改通知時,它將布爾值轉換為Visibility。 正確=>可見,錯誤=>折疊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.