「WPFデータバインディングを行う方法」の記事を読むたびに、いくつかのバリエーションを使って、時にはDataContextで、場合によっては、時にはItemssourceまたはItemSourceとDataContextの両方で、ObjectDataProviderと、これらのいずれかをXAMLまたはコードビハインドに配置するか、コードビハインドなしでXAMLからViewModelに直接バインドすることができます。WPFのデータバインディングの例の網羅的なコレクションを知っている人はいますか?
XAML自体の中で使用するための異なる構文の数十、例えばあるように思える:
<ListBox ItemsSource="{Binding Source={StaticResource Customers}}">
と
<ListBox DataContext="{StaticResource Customers}" ItemsSource="{Binding}">
これらの2つのコードサンプルは、例えば、同じことを実行します。
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>
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();
}
}
}
誰もがただ一つの特定の方法を説明し、「ここにあなたがデータバインディングを行う方法だ」と言って、代わりのでWPFデータバインディングを説明してソースを知っています、代わりににしようとすると、さまざまな方法について説明してデータバインディングについて説明し、おそらく何の長所と短所を DataContextを持っているかどうか、XAMLやコードビハインドなどでバインドしていますか?