IsEnabled property cannot be binded to a DependencyProperty and IValueConverter - c#

I have the following code:
XAML code:
<Window x:Class="combobinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:combobinding"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Window.Resources>
<local:EnumConverter x:Key="isEnabledConverter" />
</Window.Resources>
<Grid>
<TextBox Text="Hello" IsEnabled="{Binding SectionTitle, Converter={StaticResource isEnabledConverter}}" />
</Grid>
</Window>
C# Code
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static readonly DependencyProperty SectionTitleProperty =
DependencyProperty.Register(nameof(SectionTitle),
typeof(SectionTitle),
typeof(MainWindow));
public SectionTitle SectionTitle
{
get { return (SectionTitle)GetValue(SectionTitleProperty); }
set { SetValue(SectionTitleProperty, value); }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
SectionTitle = SectionTitle.TitleBlock;
}
}
public enum SectionTitle
{
Normal,
TitleBlock
}
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var sectionType = (SectionTitle)value;
if (sectionType == SectionTitle.Normal)
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
I would expect that the EnumConverter would be called as I am setting the DependencyProperty SectionTitle and any breakpoint inside the method will be hit.
However this doesn't seem to be the case; and the IsEnabled property is not being binded to SectionTitle as I wish.
What's wrong with this code?

The problem is the DataContext. The binding does not find its target.
You can set the context in the declaration of the window. Add this to the Window tag in your XAML:
DataContext="{Binding RelativeSource={RelativeSource Self}}"

Define Name property on your Window with Name="MyWindow", then use it in your binding like this:
<TextBox Text="Hello" IsEnabled="{Binding ElementName=MyWindow, Path=SectionTitle, Converter={StaticResource isEnabledConverter}}" />

You need to set the DataContext of your MainWindow. You can esaily do this inside the constructor:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
...

Related

MVVM Setting GridViewColumn width dynamically

In my mvvm application I have a listview.
I like to show/hide some columns of the
listview, depending on the state of the checkbox "Show all columns" (Here: Col1 should be showed/hidden).
That's my very simplified code. What is wrong?!
Obviously this does't work!
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="185">
<Window.Resources>
<local:ConverterHideListViewColumn x:Key="ConverterHideListViewColumn" />
</Window.Resources>
<Grid>
<ListView Height="100" Width="100">
<ListView.View>
<GridView>
<GridViewColumn Header="Col0" Width="40"/>
<GridViewColumn Header="Col1" Width="{Binding ShowAllColumns, Converter={StaticResource ConverterHideListViewColumn}}"/>
</GridView>
</ListView.View>
</ListView>
<CheckBox
Content="Show all columns"
IsChecked="{Binding ShowAllColumns, Mode=TwoWay}"
Margin="40,140,0,0">
</CheckBox>
</Grid>
</Window>
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
VM _vm;
public MainWindow ()
{
InitializeComponent ();
_vm = new VM ();
this.DataContext = _vm;
}
}
/// <summary>
/// Dummy Viewmodel
/// </summary>
public class VM : INotifyPropertyChanged
{
private bool _bShowAllColumns;
public event PropertyChangedEventHandler PropertyChanged;
public VM ()
{
ShowAllColumns = true;
}
public bool ShowAllColumns
{
get { return _bShowAllColumns; }
set { _bShowAllColumns = value; }
}
private void OnPropertyChanged (string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler (this, new PropertyChangedEventArgs (propertyName));
}
}
/// <summary>
/// Converter for setting the ListView-Column width, depending on value VM.ShowAllColumns
/// </summary>
class ConverterHideListViewColumn : IValueConverter
{
public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool bShowAllColumns = false;
double dWidth = 0;
if (value is bool)
{
bShowAllColumns = (bool) value;
dWidth = bShowAllColumns? 40 : 0;
}
return dWidth;
}
public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException ();
}
}
}
A GridViewColumn is not added to the visual tree and doesn't inherit any DataContext so you cannot bind its Width property to a source property of a view model without using a BindingProxy class as suggested here: https://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
This is all you need...
public bool ShowAllColumns
{
get { return _bShowAllColumns; }
set
{
if (_bShowAllColumns != value)
{
_bShowAllColumns = value;
OnPropertyChanged("ShowAllColumns");
}
}
}

Assigning a collection of images to a code-behind property

Okay, so I have been struggling for days to figure out how XAML is actually processing collections, and every single time I try the DependencyProperty method, the property is null. When I use ObservableCollection, and assign it a type of an Array in XAML, I get a message stating that type ArrayExtension can not be assigned to collection or dictionary.
So I am now sitting at a point where I don't know what I don't know, but I know my objective.
I want to assign multiple elements of type <Image /> to my collection in code-behind, and I have to be able to identify (preferably by integer) which "image" is being referenced in the collection.
Preferable XAML format.
<cc:MyControl.States>
<Image Source="{StaticResource PointBulletIconImage}" />
<Image Source="{StaticResource PointNumberIconImage}" />
</cc:MyControl.States>
Code-behind desired functionality
this.Image = States[CurrentState];
Instead of a collection of Image controls, your control should declare a property that holds a collection of ImageSource objects, like
public partial class MyControl : UserControl
{
public List<ImageSource> States { get; } = new List<ImageSource>();
...
}
You could now add bitmap resources in XAML like this:
<cc:MyControl>
<cc:MyControl.States>
<StaticResource ResourceKey="PointBulletIconImage"/>
<StaticResource ResourceKey="PointNumberIconImage"/>
</cc:MyControl.States>
</cc:MyControl>
The XAML of MyControl would declare an Image control, e.g. named "image"
<Image x:Name="image"/>
and you would set its Source property in code behind like this:
image.Source = States[0];
Okay, so as per Clemens's suggestion, I figured it out. The issue was that I wasn't "waiting" until after the element was loaded. It initializes the components, then takes in values, which I was forgetting. As a result, the values that are being assigned don't yet exist. Clemen's solution to use the to an ImageSource observable collection worked, but I had to wait until the control was loaded.
public ImageSource ImageSource {
get {
return GetValue(ImageSourceProperty) as ImageSource;
}
set {
SetValue(ImageSourceProperty, value);
}
}
public ObservableCollection<ImageSource> States { get; } = new ObservableCollection<ImageSource>();
public int CurrentState { get; set; }
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(PointButton));
public PointButton( ) {
CurrentState = 0;
InitializeComponent( );
Loaded += PointButton_Loaded;
}
private void PointButton_Loaded(object sender, RoutedEventArgs e) {
PreviewMouseUp += PointButton_MouseUp;
UpdateLayout( );
if(States == null)
Console.WriteLine("States is null");
else
ImageSource = States[CurrentState];
}
private void PointButton_MouseUp(object sender, MouseButtonEventArgs e) {
if(CurrentState == States.Count - 1)
CurrentState = 0;
else
CurrentState += 1;
ImageSource = States[CurrentState];
}
}
XAML
<Button x:Class="Notes.Views.Controls.PointButton"
x:Name="RootElement"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Notes.Views.Controls"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
>
<Button.Template>
<ControlTemplate>
<Image Source="{Binding ImageSource, ElementName=RootElement}" />
</ControlTemplate>
</Button.Template>
So, I got it working. Thanks for the responses guys :)
Given your names I suspect your desired behaviour is to show a different icon depending on a state property in which case you really want to leave the code behind out of it as much as possible.
I would suggest a Value Converter where you feed in the state and get back an image source or URI then just bind the images image source to the status property
here is a complete example of what this would look like
Note: Example uses c#6 syntax
WPF:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<BitmapImage x:Key="img1" UriSource="someimg1.png" />
<BitmapImage x:Key="img2" UriSource="someimg2.png" />
<BitmapImage x:Key="img3" UriSource="someimg3.png" />
<BitmapImage x:Key="img4" UriSource="someimg4.png" />
<BitmapImage x:Key="img5" UriSource="someimg5.png" />
<local:StateImageConverter
x:Key="StateImageConverter"
State1Image="{StaticResource img1}"
State2Image="{StaticResource img2}"
State3Image="{StaticResource img3}"
State4Image="{StaticResource img4}"
State5Image="{StaticResource img5}"/>
</Window.Resources>
<Window.DataContext>
<local:VeiwModel x:Name="viewModel" />
</Window.DataContext>
<StackPanel>
<ComboBox ItemsSource="{Binding AllStates}" SelectedValue="{Binding State}"/>
<Image Source="{Binding State, Converter={StaticResource StateImageConverter}}" />
</StackPanel>
</Window>
Code:
public enum States
{
State1,
State2,
State3,
State4,
State5,
}
public class StateImageConverter : IValueConverter
{
public ImageSource State1Image { get; set; }
public ImageSource State2Image { get; set; }
public ImageSource State3Image { get; set; }
public ImageSource State4Image { get; set; }
public ImageSource State5Image { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var state = value as States?;
if(state.HasValue)
{
switch (state.Value)
{
case States.State1:
return State1Image;
case States.State2:
return State2Image;
case States.State3:
return State3Image;
case States.State4:
return State4Image;
case States.State5:
return State5Image;
default:
throw new InvalidCastException();
}
}
else
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//one way only
throw new NotImplementedException();
}
}
public class VeiwModel : System.ComponentModel.INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private States state;
public States State
{
get { return state; }
set
{
state = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("State"));
}
}
public IEnumerable<States> AllStates=> Enum.GetValues(typeof(States)).OfType< States>();
}
Or if you don't want to use named properties then a variation using a list would look like:
public class StateImageConverter : IValueConverter
{
public ObservableCollection<ImageSource> Images { get; set; } = new ObservableCollection<ImageSource>();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var state = value as States?;
if(state.HasValue)
{
return Images[(int)state.Value];
}
else
throw new NotImplementedException();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//one way only
throw new NotImplementedException();
}
}
defined as
<local:StateImageConverter
x:Key="StateImageConverter">
<local:StateImageConverter.Images>
<BitmapImage UriSource="someimg1.png" />
<BitmapImage UriSource="someimg2.png" />
<BitmapImage UriSource="someimg3.png" />
<BitmapImage UriSource="someimg4.png" />
<BitmapImage UriSource="someimg5.png" />
</local:StateImageConverter.Images>
</local:StateImageConverter>

Odd behavior when trying to change a bound RadioButton in WPF

I've bound two radio buttons in my Child window to an Enum in my ViewModel which is constructed in the Main window. The binding works as expected but I have noticed a very odd behavior which I can't solve. I have provided all the code here so you can reconstruct the problem easily for yourself.
Here are the steps to see this odd behavior:
Click on the button in the MainWindow
The ChildWindow opens and the RadioButton is set to User
Choose Automatic and then Choose User again
Close the ChildWindow and reopen it again! Try to change the RadioButton to Automatic. It won't change!
<Window x:Class="RadioButtonBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Button Content="Display Child Window" Click="DisplayChildWindow"/>
</Window>
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
var viewModel = new ViewModel();
DataContext = viewModel;
}
private void DisplayChildWindow(object sender, RoutedEventArgs e)
{
var win = new ChildWindow {DataContext = (ViewModel) DataContext};
win.ShowDialog();
}
}
<Window x:Class="RadioButtonBinding.ChildWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:radioButtonBinding="clr-namespace:RadioButtonBinding"
Title="ChildWindow" Height="300" Width="300">
<Window.Resources>
<radioButtonBinding:EnumBooleanConverter x:Key="EnumBooleanConverter"/>
</Window.Resources>
<StackPanel>
<RadioButton Content="Automatic"
GroupName="CalcMode"
IsChecked="{Binding Path=CalcMode,
Converter={StaticResource EnumBooleanConverter},
ConverterParameter={x:Static radioButtonBinding:CalcMode.Automatic}}"/>
<RadioButton Content="Custom"
GroupName="CalcMode"
IsChecked="{Binding Path=CalcMode,
Converter={StaticResource EnumBooleanConverter},
ConverterParameter={x:Static radioButtonBinding:CalcMode.User}}"/>
</StackPanel>
</Window>
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private CalcMode calcMode = CalcMode.User;
public CalcMode CalcMode
{
get { return calcMode; }
set
{
calcMode = value;
RaisePropertyChanged("CalcMode");
}
}
private void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler == null) return;
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class EnumBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var paramEnum = parameter as Enum;
var valueEnum = value as Enum;
return Equals(paramEnum, valueEnum);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var parameterEnum = parameter as Enum;
if (parameterEnum == null)
return DependencyProperty.UnsetValue;
return parameterEnum;
}
}
public enum CalcMode : byte
{
Automatic,
User,
}
UPDATE:
I suspect it must be the Converter but I don't know why? It just falls into a loop.
EDIT
What about converting the enum to bool as follows?
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null || !(bool)value)
return DependencyProperty.UnsetValue;
var parameterEnum = parameter as Enum;
return parameterEnum;
}

MVVM changing grid's background color on click

I'm a true beginner in MVVM pattern. I'm trying to change the backgound of a grid on button's click. I have a xaml with a grid containing a button, and a ViewModel .cs from where i want to change the grid's background on button's click. Until there i just succeed to show up a MessageBox when i clicked...
.xaml code:
<Window x:Class="WpfSimple.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfSimple"
Title="MainWindow" Height="150" Width="370">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Button Content="Click"
Height="23"
HorizontalAlignment="Left"
Background="Gray"
Margin="75.944,47.465,0,0"
Name="btnClick"
VerticalAlignment="Top"
Width="203"
Command="{Binding ButtonCommand}"/>
<!--What is necessary to add for changing grid color ? Commandparameter ?-->
</Grid>
MainWindowViewModel.cs code:
namespace WpfSimple
{
class MainWindowViewModel
{
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get
{
return m_ButtonCommand;
}
set
{
m_ButtonCommand = value;
}
}
public MainWindowViewModel()
{
ButtonCommand=new RelayCommand(new Action<object>(ChangeBgColor));
}
public void ChangeBgColor(object obj)
{
/*HERE I WANT TO CHANGE GRID COLOR*/
}
}
}
Sorry for my bad english.
Best regards.
Fitst of all you should implement INotifyPropertyChanged in your ViewModel:
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Then, add NotifyPropertyChanged() to your properties setter.
Ok. Next, add new Property with your grid background color to your ViewModel:
private Brush _gridBackground;
public Brush GridBackground
{
get { return _gridBackground; }
set
{
_gridBackground = value;
NotifyPropertyChanged();
}
}
And bind your grid's background to your property:
<Grid Background="{Binding GridBackground}">
Finally you can just change GridBackground in the command handler:
public void ChangeBgColor(object obj)
{
GridBackground = Brushes.Blue;
}
You should remember that it's a bad practice to add WPF-classes like Brush to your code. The better way is to use IValueConverter in XAML code and BCL classes in your ViewModel. For example, you can use enumeration in ViewModel and convert it to brush in ValueConverter.
Add new enum for your ViewModel's property:
public enum GridState { Valid, Invalid }
Change property type:
private GridState _gridBackground;
public GridState GridBackground
{
get { return _gridBackground; }
set
{
_gridBackground = value;
NotifyPropertyChanged();
}
}
Add new class with value converter
public class GridStateToBackgroundColorConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
GridState val = (GridState) value;
if(val == GridState.Valid)
return Brushes.Green;
return Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
Add new static resource to your control
<UserControl.Resources>
<converters:GridStateToBackgroundColorConverter x:Key="gridStateToBackgroundColorConverter" />
</UserControl.Resources>
Update binding to your property
<Grid Background="{Binding GridBackground, Converter={StaticResource gridStateToBackgroundColorConverter}">
If you want to change the grid background color then you can use command parameter. You can pass any UI control as Command parameter. In your case pass grid to access grid in your view model.
Give the name to your grid and use that name to use as command parameter.
For this you need to implement the code like this:
<Window x:Class="WpfSimple.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfSimple"
Title="MainWindow" Height="150" Width="370">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid Name="grid">
<Button Content="Click"
Height="23"
HorizontalAlignment="Left"
Background="Gray"
Margin="75.944,47.465,0,0"
Name="btnClick"
VerticalAlignment="Top"
Width="203"
Command="{Binding ButtonCommand}"
CommandParameter="{Binding Elementname="grid"}"/>
</Grid>
After making this change to the .xaml file. Implement Parameterized Relay Command to use this passed Grid to use in your Viewmodel file.
To Implement Parameterized Relay Command Try to Implement following code:
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get
{
return m_ButtonCommand;
}
set
{
m_ButtonCommand = value;
}
}
public MainWindowViewModel()
{
ButtonCommand=new RelayCommand<Grid>(ChangeBgColor);
}
public void ChangeBgColor(Grid grid)
{
if(grid!=null)
grid.Background = Brushes.Red; //Any color you want to change.
}
I hope this will work. Thank you.

WPF radio button binding - getting an error in this code here?

Trying to get radiobuttons binding working but getting a run time error with the code below. Want the radio buttons to act such that only one can be selected at a time, and that they bind correctly in a 2 way fashion. Error text is.
"The invocation of the constructor on
type 'testapp1.MainWindow' that
matches the specified binding
constraints threw an exception"
<Window x:Class="testapp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:testapp1" Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<l:EnumBooleanConverter x:Key="enumBooleanConverter" />
</Grid.Resources>
<StackPanel >
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FirstSelection}">first selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=TheOtherSelection}">the other selection</RadioButton>
<RadioButton IsChecked="{Binding Path=VeryLovelyEnum, Converter={StaticResource enumBooleanConverter}, ConverterParameter=YetAnotherOne}">yet another one</RadioButton>
<Label Content="{Binding Path=VeryLovelyEnum}" Height="28" Name="label1" />
</StackPanel>
</Grid>
</Window>
And code:
namespace testapp1
{
public partial class MainWindow : Window
{
public TestModel _model;
public MainWindow()
{
InitializeComponent();
InitializeComponent();
_model = new TestModel();
this.DataContext = _model;
}
}
public enum MyLovelyEnum
{
FirstSelection,
TheOtherSelection,
YetAnotherOne
};
public class TestModel : DependencyObject
{
public MyLovelyEnum VeryLovelyEnum
{
get { return (MyLovelyEnum)GetValue(VeryLovelyEnumProperty); }
set { SetValue(VeryLovelyEnumProperty, value); }
}
public static readonly DependencyProperty VeryLovelyEnumProperty =
DependencyProperty.Register("VeryLovelyEnum", typeof(MyLovelyEnum), typeof(TestModel), new UIPropertyMetadata(0));
// from http://stackoverflow.com/questions/397556/wpf-how-to-bind-radiobuttons-to-an-enum
public class EnumBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
#endregion
}
}
The button & label is there from a previous test I did - I just left in...
The following declaration uses an integer instead of a default enum-value. Could be your instantiation problem...
public static readonly DependencyProperty VeryLovelyEnumProperty =
DependencyProperty.Register("VeryLovelyEnum", typeof(MyLovelyEnum), typeof(TestModel), new UIPropertyMetadata(0));
Try something like...
public static readonly DependencyProperty VeryLovelyEnumProperty =
DependencyProperty.Register("VeryLovelyEnum", typeof(MyLovelyEnum), typeof(TestModel), new UIPropertyMetadata(MyLovelyEnum.FirstSelection));

Categories

Resources