0

I have bound my group box to a INotifyPropertyChanged class.

Page Resources

    <Page.Resources>
       <current:UserAccountsStatusHandler x:Key="UserAccounts" />
    </Page.Resources>

Group Box

<GroupBox
                Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="2"
                Header="Select Action:"
                Foreground="{DynamicResource DynamicFrmFG}"
                VerticalAlignment="Stretch" HorizontalAlignment="Left"
                Height="50"
                DataContext="{StaticResource ResourceKey=UserAccounts}">

                <StackPanel 
                    Orientation="Horizontal"
                    HorizontalAlignment="Stretch" VerticalAlignment="Center"
                    Height="Auto">
                    <RadioButton
                        Content="Insert" 
                        Foreground="{DynamicResource DynamicFrmFG}" Height="16"
                        IsChecked="{Binding Path=UserAccountAction, Converter={StaticResource enumToBooleanConverter}, 
                                  ConverterParameter={x:Static enums:UserAccountActions.Insert}, UpdateSourceTrigger=PropertyChanged}"
                        Margin="0,0,10,0" 
                        Click="RadioButton_Click" />
                    <RadioButton
                        Content="Update" 
                        Foreground="{DynamicResource DynamicFrmFG}" Height="16"
                        IsChecked="{Binding Path=UserAccountAction, Converter={StaticResource enumToBooleanConverter}, 
                                  ConverterParameter={x:Static enums:UserAccountActions.Update}, UpdateSourceTrigger=PropertyChanged}"
                        Margin="0,0,10,0" 
                        Click="RadioButton_Click" />
                    <RadioButton
                        Content="Delete" 
                        Foreground="{DynamicResource DynamicFrmFG}" Height="16"
                        IsChecked="{Binding Path=UserAccountAction, Converter={StaticResource enumToBooleanConverter}, 
                                  ConverterParameter={x:Static enums:UserAccountActions.Delete}, UpdateSourceTrigger=PropertyChanged}"
                        Margin="0,0,10,0" 
                        Click="RadioButton_Click" />
                </StackPanel>
            </GroupBox>

Class

public class UserAccountsStatusHandler : INotifyPropertyChanged
{
    private UserAccountActions userAccountAction;
    public UserAccountActions UserAccountAction 
    {
        get { return userAccountAction; } 
        set 
        {
            userAccountAction = value;
            IsSaveEnabled = (userAccountAction == UserAccountActions.None) ? false : true;
            OnPropertyChanged("UserAccountAction"); 
        } 
    }

    private bool isSavedEnabled;
    public bool IsSaveEnabled { get { return isSavedEnabled; } set { isSavedEnabled = value; OnPropertyChanged("IsSaveEnabled"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

This all works as expected. I click one of the radio buttons and the property changes and the save button becomes enabled. However, I am trying to figure out how I pull those values from the Class, in the code behind the page, with out actually having to pull the DataContext of the groupbox from the UI, then calling the class.

If i try and make a new instance of the class in the code behind the page, as expected I get the default values. So far the only way I have discovered how to get/set the values is by setting the value of a variable to equal the groupboxes datacontext like so:

        var test = (UserAccountsStatusHandler)tempGroupBoxName.DataContext;
        test.IsSaveEnabled = false;

A lot of things I have read state the data layer should not ever have to know anything about the UI. So I am at a loss of how to do this then. Any help would be greatly appreciated.

Edit: Adding What I previously did which I thought was wrong also.

private UserAccountsStatusHandler mainStatusHandler;
mainStatusHandler = new UserAccountsStatusHandler();               
base.DataContext = mainStatusHandler;

At this point I could easily call mainStatusHandler to get things like is IsSavedEnabled and determine what action the user selected from UserAccountAction. The only real reason i use IsSavedEnabled is to disable the button when the tab reloads the page. To make sure they do not hit the save button without actually selecting an action first, which then enables the save button. They then have to actually hit the Save button to execute the code behind to save data to the server.

2
  • I may need to read more up on MVVM, based on the answers provided so far. I may not being grasping it like I thought. Jul 11, 2014 at 22:39
  • I updated my answer for you, providing a better example suiting your needs. From your edit, it is pretty clear you just need some brushing up on MVVM and WPF. You should not be placing this kind of stuff in your code-behind, it really belongs in the View Model. Jul 11, 2014 at 23:36

3 Answers 3

1

Since you are just using this for some form of validation, then you really need to be using an ICommand implementation. So in this case, modify your view model to implement the ICommand interface along side your INotifyPropertyChanged.

public class UserAccountsStatusHandler : INotifyPropertyChanged, ICommand
{
    private UserAccountActions userAccountAction;
    public UserAccountActions UserAccountAction
    {
        get { return userAccountAction; }
        set
        {
            userAccountAction = value;
            IsSaveEnabled = (userAccountAction == UserAccountActions.None) ? false : true;
            OnPropertyChanged("UserAccountAction");

            // Refresh the CanExecute method.
            OnCanExecuteChanged();
        }
    }

    private bool isSavedEnabled;
    public bool IsSaveEnabled { get { return isSavedEnabled; } set { isSavedEnabled = value; OnPropertyChanged("IsSaveEnabled"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public bool CanExecute(object parameter)
    {
        return userAccountAction.SomeActionSelected != null;
    }

    public event EventHandler CanExecuteChanged;
    private void OnCanExecuteChanged()
    {
        if (this.CanExecuteChanged!= null)
            this.CanExecuteChanged(this, new EventArgs());
    }

    public void Execute(object parameter)
    {
        // perform save code.
    }
}

Now in your XAML, if your groupbox has a UserAccountStatusHandler as its data context, you can use assign your Groupbox a name, and bind your button to it.

<GroupBox x:Name="UserAccountStatusGroupBox"></GroupBox>

<Button Content="Save"
        Command={Binding ElementName=UserAccountStatusGroupBox, Path=DataContext} />

When the view is loaded, the button calls CanExecute. If the return value is false, the button is auto-disabled. If it is true, it is enabled. When a property within your view model is changed, you then invoke the CanExecuteChanged handler and it will re-evaluate if the save button can be enabled or not.

In general, you should have one view model per view/user control. In this case, your view( Window/Page) should have the View Model as its data context and not the GroupBox. This is the best practice.

I recommend you read up on the Command Pattern that MVVM works hand-in-hand with. For something like this, there should be zero code-behind at all. It should all be contained in the View Model. The intent of the View Model is to support the View.

2
  • Many thanks. What you have shown does make a lot more sense to me, and I will definitely be reading more into MVVM and that link you recommended, this weekend. Jul 12, 2014 at 1:30
  • It is a good idea to read up on the pattern, then explore some of the various implementations of it available for WPF. MVVMLight is a good implementation as is Prism (albeit Prism for WPF is a bit over-kill for non enterprise\modular apps). WPF's default MVVM implementation leaves a lot to be desired. Jul 12, 2014 at 1:37
1

Generally speaking, each View you crate should have a ViewModel:

<Page.DataContext>
     <local:MyViewModel/>
</Page.DataContext>

Your UserAccountsStatusHandler could be your ViewModel in this case. But by setting it at the Page level as the DataContext, you don't need to worry quite as much about digging into the UI from the code behind.

You can just expose a property in your CodeBehind like this:

private MyViewModel ViewModel 
{
    get 
    { 
        return DataContext as MyViewModel;
    }
}

Now you can just use:

MyViewModel.IsSaveEnabled = false;

Which is nicer.

However, I would avoid putting much logic in the code-behind. I would prefer to have your button call a Save() method on the ViewModel, and then have the ViewModel update itself accordingly.

-1

Typically I don't set the DataContext of a control on my page/window, but rather set the data context of the root object itself. I also add a private property to make it easy to use if necessary (it just returns the value of DataContext cast to the class of my view model).

Then you just need to use this property, and that will give you access to the values bound to the UI.

1
  • I'd argue that you shouldn't need to have access to your view model from your code-behind. The code-behind should be used for manipulating the way a View is presented, leaving the data fetching to the bindings in XAML. The only reason I've ever needed to place view model related code in my code-behind was for instancing it with dependencies passed in via the constructor on a non-DI app. Ideally you should be fetching the data you need in your code-behind from your XAML element values themselves (var name = this.lblName.Text), giving you a layer of abstraction from the VM &your code-behind. Jul 12, 2014 at 1:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.