0

1つのデータを複数のコントロールにバインドしたいと思います。これを実現するために、 WPFに論理的な制御はありますか?たとえば、私はGrid

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>

    <TextBlock Text="{Binding Name}" />
    <Button Grid.Column="1" Grid.RowSpan="2" IsEnabled="{Binding IsSimulationRunning}" />
    <controls:PlayerControl Grid.Row="1" IsEnabled="{Binding IsLoaded}" />
</Grid>

TextBlock次のように、あるデータと別のデータにバインドしButtonたいPlayerControlと思います。

<Container DataContext="{Binding Object2}">
    <Button IsEnabled="{Binding IsSimulationRunning}" />
    <controls:PlayerControl IsEnabled="{Binding IsLoaded}" />
</Container>

どうすればこれを最善の方法で行うことができますか?

4

1 に答える 1

1

バインディングは、依存関係プロパティを含む要素のDataContextにバインドします。また、DataContextを基になるビューモデルにバインドできます。

<TextBlock DataContext="{Binding Object1}" Text="{Binding Name}" />
<Button Grid.Column="1" Grid.RowSpan="2" 
    DataContext="{Binding Object2}" IsEnabled="{Binding IsSimulationRunning}" />
<controls:PlayerControl Grid.Row="1" 
    DataContext="{Binding Object2}" IsEnabled="{Binding IsLoaded}" />

ビューモデルが次のようになっている場合:

public class PlayerViewModel {        
    public TrackViewModel Object1 { get; set; }
    public PlaybackViewModel Object2 { get; set; }
}
public class TrackViewModel { public string Name { get; set; } }
public class PlaybackViewModel { 
    public bool IsLoaded { get; set; } 
    public bool IsSimulationRunning { get; set; }
}

この場合、オブジェクトに直接バインドできます。重要な点は、1つの共通ビューモデルに2つのオブジェクトが必要であるということです。

<TextBlock Text="{Binding Path=Object1.Name}" />
<Button Grid.Column="1" Grid.RowSpan="2" IsEnabled="{Binding Path=Object2.IsSimulationRunning}" />
<controls:PlayerControl Grid.Row="1" IsEnabled="{Binding Path=Object2.IsLoaded}" />
于 2012-04-07T07:10:23.423 に答える