Browse Source

Merge pull request #11227 from rabbitism/combobox

Support DisplayMemberBinding in ComboBox SelectedItem
pull/11247/head
Max Katz 3 years ago
committed by GitHub
parent
commit
007d2b2a0d
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 15
      samples/ControlCatalog/Pages/ComboBoxPage.xaml
  2. 15
      samples/ControlCatalog/ViewModels/ComboBoxPageViewModel.cs
  3. 17
      src/Avalonia.Controls/ComboBox.cs

15
samples/ControlCatalog/Pages/ComboBoxPage.xaml

@ -98,6 +98,21 @@
<ComboBoxItem>Inline Item 3</ComboBoxItem>
<ComboBoxItem>Inline Item 4</ComboBoxItem>
</ComboBox>
<ComboBox WrapSelection="{Binding WrapSelection}" ItemsSource="{Binding Values}" DisplayMemberBinding="{Binding Name}">
</ComboBox>
<ComboBox WrapSelection="{Binding WrapSelection}" ItemsSource="{Binding Values}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"></TextBlock>
<TextBlock Text="{Binding Id}"></TextBlock>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</WrapPanel>
<CheckBox IsChecked="{Binding WrapSelection}">WrapSelection</CheckBox>

15
samples/ControlCatalog/ViewModels/ComboBoxPageViewModel.cs

@ -16,5 +16,20 @@ namespace ControlCatalog.ViewModels
get => _wrapSelection;
set => this.RaiseAndSetIfChanged(ref _wrapSelection, value);
}
public ObservableCollection<IdAndName> Values { get; set; } = new ObservableCollection<IdAndName>
{
new IdAndName(){ Id = "Id 1", Name = "Name 1" },
new IdAndName(){ Id = "Id 2", Name = "Name 2" },
new IdAndName(){ Id = "Id 3", Name = "Name 3" },
new IdAndName(){ Id = "Id 4", Name = "Name 4" },
new IdAndName(){ Id = "Id 5", Name = "Name 5" },
};
}
public class IdAndName
{
public string Id { get; set; }
public string Name { get; set; }
}
}

17
src/Avalonia.Controls/ComboBox.cs

@ -443,7 +443,22 @@ namespace Avalonia.Controls
}
else
{
SelectionBoxItem = item;
if(ItemTemplate is null && DisplayMemberBinding is { } binding)
{
var template = new FuncDataTemplate<object?>((_, _) =>
new TextBlock
{
[TextBlock.DataContextProperty] = item,
[!TextBlock.TextProperty] = binding,
});
var text = template.Build(item);
SelectionBoxItem = text;
}
else
{
SelectionBoxItem = item;
}
}
}

Loading…
Cancel
Save