似乎每次我阅读一篇关于"如何进行WPF数据绑定"的文章时,都会使用一些不同的变体,有时使用DataContext,有时没有,有时使用Itemssource或同时使用Itemssource和DataContext,还有ObjectDataProvider,你可以在XAML或代码隐藏中有任何这些,或者没有代码隐藏,并直接从XAML绑定到您的ViewModel.
似乎在XAML本身中有许多不同的语法,例如:
<ListBox ItemsSource="{Binding Source={StaticResource Customers}}">
Run Code Online (Sandbox Code Playgroud)
和
<ListBox DataContext="{StaticResource Customers}" ItemsSource="{Binding}">
Run Code Online (Sandbox Code Playgroud)
例如,这两个代码示例执行相同的操作:
1.使用没有代码隐藏的ObjectDataProvider:
<Window x:Class="TestDataTemplate124.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestDataTemplate124"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider x:Key="Customers"
ObjectType="{x:Type local:Customer}"
MethodName="GetAllCustomers"/>
</Window.Resources>
<StackPanel>
<ListBox DataContext="{StaticResource Customers}" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding LastName}"/>
<TextBlock Text=" ("/>
<TextBlock Text="{Binding Age}"/>
<TextBlock Text=")"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
2.没有DataContext的示例:
<Window x:Class="TestDataTemplate123.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestDataTemplate123"
Title="Window1" Height="300" Width="300">
<StackPanel>
<ListBox x:Name="ListBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding LastName}"/>
<TextBlock Text=" ("/>
<TextBlock Text="{Binding Age}"/>
<TextBlock Text=")"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Window>
using System.Collections.ObjectModel;
using System.Windows;
namespace TestDataTemplate123
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ListBox1.ItemsSource = Customer.GetAllCustomers();
}
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道,通过的,而不是只说解释WPF数据绑定源的"这里是你怎么做绑定",然后解释一个特定的方式,而是试图解释各种方式去绑定和显示或许有什么优点和缺点的例如,是否具有DataContext,在XAML中绑定或代码隐藏等?
| 归档时间: |
|
| 查看次数: |
647 次 |
| 最近记录: |