如何在我的UWP App中为ComboBox定义自定义模板,对于Dropdown我需要一个带标签的复选框,但是当用户选择任何选项时我只需要在comobox中显示标签
我尝试了这个,但我没有工作:
<ComboBox x:Name="cbCountry"
Header="Country"
Margin="10,5"
HorizontalAlignment="Stretch"
Style="{StaticResource ComboBoxStyle}">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}"></CheckBox>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<TextBlock Text="{Binding}"/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
答案 0 :(得分:1)
<Page.Resources>
<local:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Page.Resources>
<ComboBox x:Name="cbState" DropDownClosed="cbState_DropDownClosed" DropDownOpened="cbState_DropDownOpened" Margin="75,287,0,0" Width="169" ItemContainerStyle="{StaticResource ComboBoxItemStyle1}" Style="{StaticResource ComboBoxStyle1}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox Content="{Binding}"
Visibility="{Binding IsCheckBoxVisible, Mode=TwoWay, Converter={StaticResource BooleanToVisibilityConverter}, UpdateSourceTrigger=PropertyChanged}" >
</CheckBox>
<TextBlock Text="{Binding State_Name}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
private void cbState_DropDownClosed(object sender, object e)
{
foreach (var item in (sender as ComboBox).Items)
{
(item as State).IsCheckBoxVisible = false;
}
}
private void cbState_DropDownOpened(object sender, object e)
{
foreach(var item in (sender as ComboBox).Items)
{
(item as State).IsCheckBoxVisible = true;
}
}
转换器类
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var boolValue = System.Convert.ToBoolean(value);
return boolValue ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return ((Visibility)value == Visibility.Visible) ? true : false;
;
}
}
模型类。实现INotifyPropertyChanged以反映UI中的更改(复选框可见性更改)
public class State:INotifyPropertyChanged
{
public string State_Name { get; set; }
public object State_Id { get; set; }
bool isCheckBoxVisible;
public bool IsCheckBoxVisible
{
get { return isCheckBoxVisible; }
set
{
if (value != isCheckBoxVisible)
{
isCheckBoxVisible = value;
OnPropertyChanged("IsCheckBoxVisible");
}
}
}
public State(string name,object id,bool visibility=false)
{
State_Name = name;
State_Id = id;
IsCheckBoxVisible = false;
}
public event PropertyChangedEventHandler PropertyChanged;
public override string ToString()
{
return State_Name;
}
void OnPropertyChanged(string propertyName)
{
// the new Null-conditional Operators are thread-safe:
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}