我想将一个数据绑定到多个控件。在 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>
我怎样才能以最好的方式做到这一点?
答案 0 :(得分: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; }
}
在这种情况下,您可以直接绑定到对象。重点是您需要在一个通用视图模型中拥有两个对象。
<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}" />