简体   繁体   中英

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)?

如果每个用户控件都有Account属性,它可以在自己的文本框、网格等中进行绑定,例如

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM