nighthawk
nighthawk

Reputation: 842

Update UserControl when parent item is changed

What is the proper way (MVVM) to handle following situation? We have an window/user control which hosts few user controls and grid. When we select grid item, SelectedItem="{Binding SelectedAccount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" is updating SelectedAccount property on user controls

<TabItem Header="{x:Static p:Resources.Basic}">
    <DockPanel>
       <accounts:UCBasic x:Name="UCBasic" SelectedAccount="{Binding SelectedItem, ElementName=gridMain}"></accounts:UCBasic>
    </DockPanel>
</TabItem>
    <TabItem Header="{x:Static p:Resources.AdditionalData}">
    <DockPanel>
          <accounts:UCAdditionalData x:Name="UCAdditionalData" SelectedAccount="{Binding SelectedItem, ElementName=gridMain}"></accounts:UCAdditionalData >
    </DockPanel>
    ... more user controls ...
</TabItem>

using their DependencyProperty. Now, how would I write PageModel for above user controls (UCBasic, UCAdditionalData) so they can load/show more data depending on SelectedAccount from grid. There is dirty way of using property changed event but I don't think it should be done that way. Each user control has this:

public Account SelectedAccount
{
    get { return (Account)GetValue(SelectedAccountProp); }
    set
    {
        SetValue(SelectedAccountProp, value);
    }
}
public static readonly DependencyProperty SelectedAccountProp = DependencyProperty.Register("SelectedAccount", typeof(Account), typeof(UCBasic));

Essentialy, how I would notify this user control that SelectedAccount value is changed and it should update itself (its own textboxes, grids and so on)?

Upvotes: 0

Views: 407

Answers (2)

ASh
ASh

Reputation: 35720

if each user control has Account property, it can do bindings in its own textboxes, grids and so on, e.g.

<TextBox Text="{Binding Account.Name, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

Upvotes: 1

AnnaS
AnnaS

Reputation: 76

1) you can use INotifyPropertyChanged implementation in your ViewModel (if will send notification to update changed ViewModel property on View) 2) If you use one ViewModel for both user controls 1 option should help you immediately. If you use different ViewModels you should update the secornd user control view model in code when the first user control is updated.

Upvotes: 0

Related Questions