I have an enum:
public enum ImageTextLocation
{
Left,
Top,
Right,
Bottom
}
And a custom UserControl
that contains dependency property of that enum.
<Button Content="{Binding ButtonText}"
Command="{Binding Command}"
Style="{StaticResource ImageButtonStyle}">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border x:Name="border"
Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<DockPanel>
<ContentPresenter DockPanel.Dock="{Binding Path=TextLocation, Converter={StaticResource EnumToDockConvert}}"
Margin="2,6,0,2"/>
</DockPanel>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
public partial class ImageButtonControl : UserControl
{
public ImageTextLocation TextLocation
{
get => (ImageTextLocation)GetValue(TextLocationProperty);
set => SetValue(TextLocationProperty, value);
}
public static readonly DependencyProperty TextLocationProperty =
DependencyProperty.Register(
"TextLocation",
typeof(ImageTextLocation),
typeof(ImageButtonControl),
new FrameworkPropertyMetadata(ImageTextLocation.Left,
PropertyChangedCallback) { BindsTwoWayByDefault = true, }
);
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var imageButton = (ImageButtonControl)d;
var newLocation = (ImageTextLocation)e.NewValue;
switch (newLocation)
{
case ImageTextLocation.Left:
imageButton.SetCurrentValue(TextLocationProperty, ImageTextLocation.Left);
break;
case ImageTextLocation.Right:
imageButton.SetCurrentValue(TextLocationProperty, ImageTextLocation.Right);
break;
}
}
}
I have added created a converter that converts from ImageTextLocation
to Dock
:
public class EnumToDockConverter : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
if(value == null)
return Dock.Left;
ImageTextLocation location = (ImageTextLocation)value;
var dock = Enum.Parse(typeof(Dock), location.ToString());
return dock;
}
public object ConvertBack(object value,
Type targetType,
object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
And added an instance of the converter to the resources of my UserControl
:
<coverter:EnumToDockConverter x:Key="EnumToDockConvert"/>
Then, I try to set the DockPanel.Dock
of the custom control using TextLocation="{Binding ImageTextPosition}"
, where ImageTextPosition
is the string property of my view model bound to the UserControl
.
<controls:ImageButtonControl TextLocation="{Binding ImageTextPosition}"/>
DockPanel's Dock does not set when I set the dependency property.