Bbinding combobox within dataform to view model property outside dataform's context

為{幸葍}努か 提交于 2019-11-28 13:05:49
Simon_Weaver

Here's what I did (tested and works):

Within a DataForm this won't work (because its a DataTemplate) :

<ComboBox MinWidth="150" DisplayMemberPath="Name" Name="cbCompanies"
          SelectedItem="{Binding TODOCompany,Mode=TwoWay}" 
          ItemsSource="{Binding ElementName=control, Path=ParentModel.Companies}" />

But you can do this instead:

<ComboBox MinWidth="150" DisplayMemberPath="Name" Name="cbCompanies"
          SelectedItem="{Binding TODOCompany,Mode=TwoWay}" 
          Loaded="cbCompanies_Loaded"/>

Code behind:

private void cbCompanies_Loaded(object sender, RoutedEventArgs e)
{
    // set combobox items source from wherever you want
    (sender as ComboBox).ItemsSource = ParentModel.Companies;
}

if you set your datacontext using locator in this way

DataContext="{Binding FormName, Source={StaticResource Locator}}"

<ComboBox ItemsSource="{Binding FormName.ReasonsComboList, Source={StaticResource Locator}, Mode=OneWay}"
          DisplayMemberPath="Reason" SelectedValuePath="Id"
          SelectedValue="{Binding ReasonForEndingId, Mode=TwoWay}"/>

tested and working

I haven't tested this with your exact scenario, but you should be able to reference the DataContext of some parent element when binding the ItemsSource of the ComboBox. Basically using Silverlight's element-to-element binding to actually bind to some property on the parent container's DataContext instead of the current element's DataContext.

For example, if your main ViewModel was the DataContext of the LayoutRoot element you should be able to do something like this:

<ComboBox x:Name="EndReasonCombo" ItemsSource="{Binding DataContext.ReasonsComboList, ElementName=LayoutRoot}" DisplayMemberPath="Reason" SelectedValuePath="Id" SelectedValue="{Binding ReasonForEndingId, Mode=TwoWay}"/>

Creating a Silverlight DataContext Proxy to Simplify Data Binding in Nested Controls

Disclaimer: This may not actually work for the DataForm, but is suitable for the same problem when using a DataGrid. but I'm putting it here as an answer because it was an interesting read and helped me understand some things when I experienced the same problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!