I am beginning WPF, and I am having a bit of a hard time implementing data binding.
Specifically, I have created a simple user control which holds a Label and a Button.
For this user control, I have created a ViewModel which holds just two properties, string “Text” and SimpleEnum “Status”.
The point of the control is to display a status of something, like “Connected” yes/no, etc. The background color of the button indicates the status.
My XAML looks something like this
<Control.DataContext>
<vm:OnOffStatusViewModel />
</Control.DataContext>
<Label x:Name="label1" Height="Auto" HorizontalAlignment="Left" Content="{Binding Text}" Width="280" />
<Button Style="{StaticResource GlassButton}" Height="14" Width="14" Background="{Binding Status}" Grid.Column="1" />
with xmlns:vm="clr-namespace:Controls"
The code-behind has a property ViewModel exposing the view model, implementing INotifyPropertyChanged, and initializes as _viewModel = (OnOffStatusViewModel) DataContext;
Now, in my view that is using this control, I have managed to set the Text to something, as I in my implementing view code-behind have onOffStatus1.ViewModel.Text = ..., however, the status is set by enum, and is as such not really bindable to the background property of the button.
My questions related to this:
-
Is the way I have done the control correct? If not, what is the proper way of implementing data binding in user controls?
-
How can I have my enum status update the background property of the button using binding?
I would take a slightly different approach than the other answers here, I like to put the code and logic into my view models directly, so here’s how I would do it:
In the VM:
Since your button background is bound to a property on your view model, then you have the freedom to change that in reaction to whatever is going on in your view model without needing to move logic or code out to converters and templates.