简体   繁体   中英

C# WPF Binding to DataBase

Hei all. If something would be not clear then please tell

I have dataGrid and TreeView. I have loaded data base as Entity Data Model and some tables. One of these tables "relation" should show to the datagrid. But its (relation table) column depend of the other tables as system,model,function and device. In the Data grid should be 4 columns which contain names of these system,model,function and device. (the picture 1 as should be)

Problem in the how it all show. DataSource don't work well... see picture 2.

<Grid DataContext="{StaticResource relationsViewSource}">
        <DataGrid AutoGenerateColumns="True" Name="gridInventory" HorizontalContentAlignment="Right" Margin="255,12,12,128" ItemsSource="{Binding}" />
        <StackPanel Height="391" HorizontalAlignment="Left" Margin="10,10,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="239" DataContext="{StaticResource systemsViewSource}" >
            <TreeView Height="391" Name="treeView1" Width="239" VerticalContentAlignment="Top" HorizontalAlignment="Left" VerticalAlignment="Top" ItemsSource="{Binding}" />
        </StackPanel>
    </Grid>

Picture 1: 在此输入图像描述

Picture2: 在此输入图像描述

在此输入图像描述

You are binding both the TreeView and some of your DataGrid columns to an object, but not telling WPF how to draw the object. When WPF doesn't know how to draw an object , it by default draws it using a TextBlock with the Text bound to the object's .ToString()

You need to set the ItemTemplate to tell WPF how to draw your individual objects, such as this:

<TreeView.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding Name}" />
    </DataTemplate>
</TreeView.ItemTemplate>

You could also use an implicit DataTemplate to tell WPF how to draw specific objects. This is just a DataTemplate that specifies a DataType without a Key , and WPF will use it anytime it tries to render an object of the specified type.

If you want to avoid removing AutoGenerateColumns="True" and manually specifying your DataGrid's columns, this is probably the method to use.

<DataGrid.Resources>
    <DataTemplate DataType="{x:Type local:Device}">
        <TextBlock Text="{Binding Name}" />
    </DataTemplate>
</DataGrid.Resources>

The TreeView you would need to set the Path on the Binding to the property you want to display,

The Devices is a collection and you need to put a Listview in there or something that will display a collection and then put a DataTemplate on it to display what you need, either that or bind to a converter to return a static string representation of the Device list

Or just get someone to do it all for you as seems the case on here lol

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