0

我想将一个数据绑定到多个控件。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 个公共视图模型中拥有两个对象。

<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 回答