1

シンプルな XAML ユーザー コントロールを使用して、DataContext をコード ビハインド (xaml.cs) ファイルに設定したいと思います。

XAML で DataContext と Itemssource を設定したいので、コンボボックスに ListOfCars プロパティを設定できます

XAML

<UserControl x:Class="Sample.Controls.MyControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="85" d:DesignWidth="200">
    <Grid Height="85" Width="200" Background="{StaticResource MainContentBackgroundBrush}">
        <StackPanel Orientation="Vertical">                
            <ComboBox Height="23.338" x:Name="CarList" />                
        </StackPanel>    
    </Grid>
</UserControl>

コードビハインド

public List<Cars> ListOfCars
{
  get { return _store.ListCars(); }
}

つまり、コード ビハインドでこれを行う代わりに、XAML でバインドを設定するにはどうすればよいですか?

public MyControl()
{
  InitializeComponent();
  _store = new Store();
  CarList.ItemsSource = _store.ListCars();
  CarList.DisplayMemberPath = "Name";
}
4

2 に答える 2

1

をバインドするだけItemsSourceです。

<ComboBox ItemsSource="{Binding ListOfCars}"/>

そして、UserControl の場合:

<MyControl DataContext="{Binding *viewModel*}"/>

DataContext定義では何をバインドするかわからないため、定義ではなく UserControl が使用されている場所をバインドする必要があります。は自動的にコントロールのコンテキスト内にあるため、追加の作業なしComboboxで にバインドできます。DataContext

リソースへのバインドの例:

<Application.Resources>
  ...
  <viewmodels:ViewModelLocator x:Key="ViewModelLocator"/>
  ...
</Application.Resources>


<MyControl DataContext="{Binding Source={StaticResource ViewModelLocator}}"/>

これにより、ViewModelLocator のインスタンスが作成され、コントロールの DataContext がそのリソースにバインドされます。

于 2012-09-07T13:36:20.723 に答える
1

そうしないくださいDataContext。 . UserControl.Name代わりにandElementNameバインディングを使用します (または) RelativeSource

于 2012-09-07T13:39:05.427 に答える