简体   繁体   中英

Bind a combobox to another dataset than the datacontext in WPF

Let me explain my challenge. I have a dataset with a datatable that is assigned to the datacontext. One of the fields is a category. All the category names are in another datatable (one to many relationship).

I want the combobox to display all the names in the categories datatable with the correct selected value from the datacontext datatable. So if I change category, datatable1 will be updated with the selectedValue from the combobox.

I read something about a ObjectDataProvider, but I didnt get it to work. How can I manage to get this to work?

Use like this

<UserControl x:Class="ButtonEffects.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300" Name="uc">
    <Grid>
                <ComboBox ItemsSource="{Binding ElementName=uc,Path=Categories}" 
              DisplayMemberPath="CategoryName" SelectedValuePath="Id" 
              SelectedValue="{Binding SelectedCategoryId}"/>
    </Grid>
</UserControl>

Categories being a property in you codebehind.The itemsouce will be populated from the categories table and your selectedvalue will be updated in your datacontext datatable.Hope this helps

EDIT

If your datacontext is a dataset then the selectedvalue should be like

SelectedValue="{Binding datatable1/SelectedCategoryId}"

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