2012-04-14 128 views
2

我想创建一个简单的程序,允许用户选择文件并向其中添加元数据。DataGrid上的双向绑定

我创建了一个ListBox,允许用户将文件拖放到其上。我抓住路径并将其保存到一个对象中。然后我在ListBox中显示文件名。

我希望这样,当用户选择列表框中的项目时,我可以显示文件中的元数据,并允许他们添加更多内容并编辑它。

现在我有一个存储路径和<string, string>字典的类项,其中Key是元数据的名称,并且Value是很好的值。

我已经尝试使用DataGrid,也许这是错误的控件来使用,绑定到词典。这似乎不是正确的方式,因为它不实现INotifyPropertyChanged接口。

我可以创建我自己的类,并手动更新DataGrid,但它似乎是一个工作,我不知道如何正确DataBind。

XAML

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    x:Class="MetadataAdder.MainWindow" 
    Title="Metadata Adder" Height="480" Width="640"> 
<Grid> 
    <Button x:Name="Add_BTN" Content="Add" HorizontalAlignment="Left" Margin="10,410,0,0" VerticalAlignment="Top" Width="50" Click="Add_Click"/> 
    <Button x:Name="Remove_BTN" Content="Remove" HorizontalAlignment="Left" Margin="241,410,0,0" VerticalAlignment="Top" Width="50" Click="Remove_Click"/> 
    <ListBox x:Name="File_List" HorizontalAlignment="Left" Height="364" Margin="10,31,0,0" VerticalAlignment="Top" Width="281" AllowDrop="True" Drop="FilesDropped" ItemsSource="{Binding Item_List}" SelectionChanged="Item_Selected"/> 
    <DataGrid 
     x:Name="MetadataGrid" 
     HorizontalAlignment="Left" 
     Margin="311,31,0,0" 
     VerticalAlignment="Top" 
     Height="364" 
     Width="303" 
     d:LayoutOverrides="GridBox" 
     CanUserAddRows="False" 
     CanUserDeleteRows="False" 
     CanUserReorderColumns="True" 
     CanUserResizeColumns="True" 
     CanUserResizeRows="True" 
     CanUserSortColumns="True" 
     /> 
    <Label Content="Files to add Metadata to" HorizontalAlignment="Left" Margin="10,0,0,0" VerticalAlignment="Top"/> 
    <Label Content="Metadata" HorizontalAlignment="Left" Margin="313,5,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.474,0.115"/> 

</Grid> 

回答

1

另一种方法,将工作很好地为您将创建自己的实现INotifiyPropertyChanged并包含元数据的键和值属性的FileMetadata对象。

然后将您的FileMetadata对象集合存储在ObservableCollection中并绑定到您的DataGrid。

这将允许单个元数据项目将其值保存到更改通知系统,并允许DataGrid在添加或删除任何元数据项目时自动更新。

+0

这是一个有趣的方法。好的,我会研究它。 – 2012-04-15 03:19:30

+0

这比我想象的要容易得多。 – 2012-04-16 13:08:45