[英]Hide WPF ComboBox without visible items in XAML
在折疊所有ComboBox項時,是否存在一種純粹的XAML方式來隱藏ComboBox?
例如,我有一個組合框:
<ComboBox ItemsSource="{Binding Persons}">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Visibility" Value="{Binding IsAlive, Converter={StaticResource BoolToVis}}" />
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
預期的行為:如果所有人都死了,則組合框不可見,但是如果至少一個人還活着,則組合框可見(並且僅顯示活着的人)
我已經在代碼中使用CollectionViewSource
, Filter
和應用了filter之后的CollectionViewSource.View
的元素計數在代碼中實現了此行為,但是我更喜歡在沒有代碼行為的情況下僅在XAML中實現該行為。
編輯:我需要在樣式表的所有ComboBox中可用的通用解決方案,而不是分配給Person類型或IsAlive屬性...因此解決方案應僅取決於所包含項目的可見性屬性
如果items屬性為null,為空或其中的所有項目都不可見(Visibility.Collapsed),則可以使用此附加屬性隱藏組合框。
創建一個新的類ComboBoxExt(或任何您想調用的類),然后添加一個附加屬性。 (提示:您可以在Visual Studio中輸入“ propa”,然后選擇兩次制表符,它將為您提供附加屬性的模板)
public class ComboBoxExt
{
public static bool GetHideOnEmpty(DependencyObject obj)
{
return (bool)obj.GetValue(HideOnEmptyProperty);
}
public static void SetHideOnEmpty(DependencyObject obj, bool value)
{
obj.SetValue(HideOnEmptyProperty, value);
}
public static readonly DependencyProperty HideOnEmptyProperty =
DependencyProperty.RegisterAttached("HideOnEmpty", typeof(bool), typeof(ComboBoxExt), new UIPropertyMetadata(false, HideOnEmptyChanged));
private static void HideOnEmptyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var cbox = d as ComboBox;
if (cbox == null)
return;
HideComboBox(cbox, (bool)e.NewValue);
}
//This is where we check if all the items are not visible
static void HideComboBox(ComboBox cbox, bool val)
{
//First, we have to know if the HideOnEmpty property is set to true.
if (val)
{
//Check if the combobox is either null or empty
if (cbox.Items == null || cbox.Items.Count < 1)
cbox.Visibility = Visibility.Collapsed; //Hide the combobox
else
{
bool hide = true;
//Check if all the items are not visible.
foreach (ComboBoxItem i in cbox.Items)
{
if (i.Visibility == Visibility.Visible)
{
hide = false;
break;
}
}
//If one or more items above is visible we won't hide the combobox.
if (!hide)
cbox.Visibility = Visibility.Visible;
else
cbox.Visibility = Visibility.Collapsed;
}
}
}
}
現在,您可以在所需的每個組合框中重復使用附加的屬性。 您只需要將HideOnEmpty設置為true。
<ComboBox local:ComboBoxExt.HideOnEmpty="True"/>
使用此解決方案,您將無需編寫任何代碼,並且可以在所需的每個組合框上重用附加的屬性HideOnEmpty。
您“過濾”組合框項目的方法不正確,並且效果很差[1]。 您應該使用CollectionView
/ CollectionViewSource
來過濾Persons
集合,並且不要在ItemContainerStyle
分配可見性。 完成此操作后,可以使用綁定的CollectionView.IsEmpty
屬性在ComboBox.Visibility
屬性中使用簡單的綁定和轉換器。
[1]關於性能:當前,將在評估可見性綁定之前為每個Person
對象創建一個容器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.