【发布时间】:2013-03-14 14:13:47
【问题描述】:
我有一个简单的(我认为)应用程序,它可以将 SQL 数据库读入我程序中的变量,然后我需要使用我读取的数据更新在 XAML 中定义的网格视图。我受限于 .NET 3.5 的代码。我在有关 XAML、MS .NET 帮助和 Web 其他地方的书籍上进行的所有搜索都显示了无数从 ASP.NET 执行此操作的示例,但没有一个来自 C#-XAML 组合的示例。我发现在 XAML ++much++ 中做简单的事情比在 Winforms 中做同样的事情更加困难和复杂,我只是不明白这一点。特别是,在我看来,数据绑定是一门魔法。有人可以看看我的 XAML 并告诉我需要做什么或更改以从我的 C# 代码隐藏中填充此控件吗?
这是我的 XAML:
<Window x:Class="UCCResourceManager.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="UCC Resource Mangler" Height="350" Width="700">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="250"/>
<RowDefinition />
</Grid.RowDefinitions>
<ListView Name="grdResource"
ItemsSource="{Binding}"
Grid.Row="0">
<ListView.View>
<GridView AllowsColumnReorder="false"
ColumnHeaderToolTip="UCC Resource Table">
<GridViewColumn DisplayMemberBinding="{Binding Path=ID}"
Header="ID"
Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=LocationID}"
Header="LocationID"
Width="75"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Type}"
Header="Type"
Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Name}"
Header="Name"
Width="200"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Enabled}"
Header="Enabled"
Width="50"/>
<GridViewColumn DisplayMemberBinding="{Binding Path=Flags}"
Header="Flags"
Width="50"/>
</GridView>
</ListView.View>
</ListView>
<Button Name="btnOK"
Content="OK"
Grid.Row="1"
Width="100"
Height="20
" Click="btnOK_Click" />
</Grid>
</Window>
【问题讨论】:
-
你想,把你的对象放在后面的代码中,然后把它添加到你的数据网格中?
-
I've found doing simple things in XAML ++much++ more difficult and involved than doing the same thing in Winforms,- 那是因为您正试图以 winforms 的心态使用 WPF。 WPF 实际上比 winforms 简单得多,因为它允许更高级别的自定义和可伸缩性,而无需求助于一堆 HACKS(例如所有者绘制和所有这些东西)。如果您希望在 WPF 中取得成功,您必须了解 UI is not Data。 -
data binding seems to me to be a black art.- WPF 中的数据绑定远远优于(假定的)winforms 中的数据绑定。发布您要绑定的对象的代码。实际上,发布您的DataContext的整个代码。 -
and tell me what I need to do or change to populate this control from my C# code-behind?- 你不应该在 WPF 中使用代码。必须有一个ViewModel,并且 UI 必须收集其数据并与ViewModel交互。您不得在代码中操作 UI 元素。 UI 元素和可视化树是复杂的东西,使用正确的技术比尝试自己操作这些类更好。