There are lot of approaches to achieve that:
Approach 1
The ProvideValue
method of a markup extension takes a parameter of type IServiceProvider
, which provides, among others, a IProvideValueTarget
service. This interface exposes property TargetObject
which allow to retrieve the target object (combobox in your case).
You can set SelectedValuePath
on that like this:
public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
if (target != null && target.TargetObject is ComboBox)
{
((ComboBox)target.TargetObject).SelectedValuePath = "Value";
}
var enumValues = Enum.GetValues(EnumType);
return (
from object enumValue in enumValues
select new EnumMember
{
Value = enumValue,
Display = GetDescription(enumValue)
}).ToArray();
}
Approach 2
In case all comboboxes in your app will be binded to wrapper class EnumMember
, you can define it under global style of ComboBox under Application.Resources
so that you don't have to duplicate it for each and every comboBox.
Even in case, you are not binding ComboBox to enum value, SelectedValuePath can be overriden per instance.
<Application.Resources>
<Style TargetType="ComboBox">
<Setter Property="SelectedValuePath" Value="Value"/>
</Style>
</Application.Resources>
Approach 3
You can subclass ComboBox and OnItemsSourceChanged
, set SelectedValuePath to Value
in case ItemsSource is array of EnumMember class.
public class MyComboBox : ComboBox
{
protected override void OnItemsSourceChanged(IEnumerable oldValue,
IEnumerable newValue)
{
if (newValue != null &&
newValue.GetType().Equals(typeof(EnumSource.EnumMember[])))
{
SelectedValuePath = "Value";
}
base.OnItemsSourceChanged(oldValue, newValue);
}
}
usage in XAML:
<my:MyComboBox ItemsSource="{my:EnumSource {x:Type my:Options}}"
SelectedValue="{Binding Path=CurrentOption}"/>
On a side note sine you created own markup extension, you don't need Binding
at all. You can bind ItemsSource
like this:
<ComboBox ItemsSource="{my:EnumSource {x:Type my:Options}}"
SelectedValue="{Binding CurrentOption}"/>