Peter
Peter

Reputation: 1894

Accessing a component in a ViewModel C#

I have a class that extends ViewModelBase in C#. There is already a trigger on a checkbox:

public bool PrintPackingCode
{
    get
    {
        return this.reportConfiguration.PrintPackingCode;
    }

    set
    {
        this.reportConfiguration.PrintPackingCode = value;
        this.OnPropertyChanged("PrintPackingCode");
    }
}

I want to hook into that event and render a GroupBox to disable, yet I can't find a way to access the GroupBox. In the .xaml I gave my Box a name of PackingcodeGroupBox. All methods and hint I found weren't aplieable. My tries inculded:

Direct Access: PackingcodeGroupBox.Enabled = false;
Using a x:Name
this.Resources["mykey"]

Here some more Code:

//At program start assign the view it's view model:
new SmlKonfigurationWindow(new SmlKonfigurationWindowVm(reportConfiguration, smlKonfigurationDialogVm));

public SmlKonfigurationWindow(ISmlKonfigurationWindowVm viewModel)
{
   this.DataContext = viewModel;
   this.viewModel = viewModel;

   this.InitializeComponent();
   this.ShowDialog();
}

The xaml:

<CheckBox Content="Content" IsChecked="{Binding Path=PrintPackingCode, UpdateSourceTrigger=PropertyChanged}" Name="PrintPackingCode"/>
<GroupBox Header="Verpackungscode" Name="VerpackungscodeGroupbox">
   //Stuff to be disabled                      
</GroupBox>

Upvotes: 1

Views: 147

Answers (2)

ΩmegaMan
ΩmegaMan

Reputation: 31656

On your vm create a new property say

private bool _isGroupEnabled;

public bool IsGroupEnabled
{
    get
    {
        return _isGroupEnabled;
    }

    set
    {
        _isGroupEnabled = value;
        this.OnPropertyChanged("IsGroupEnabled");
    }
}

Now tie into the notify process by adjusting your set for PrintPackingCode

   set
    {
        this.reportConfiguration.PrintPackingCode = value;
        IsGroupEnabled = !value; // reverse of packing to enable/disable.
        this.OnPropertyChanged("PrintPackingCode");
    }

Now bind your groupbox as such:

isEnabled = "{Binding IsGroupEnabled}"

Upvotes: 1

Robert
Robert

Reputation: 2533

IsEnabled is ambiental property which means that if you disable the GroupBox all controls inside that group box will also be disabled.

Try to add a binding on GroupBox like so:

IsEnabled="{Binding PrintPackingCode}"

You can also bind IsEnabled to check box if you give name to the check box.

<CheckBox x:Name="myCheckBox" .../>
<GroupBox IsEnabled="{Binding ElementName=myCheckBox, Path=IsChecked}"/>

Upvotes: 2

Related Questions