MainWindow.xaml:
<Window x:Class="MyApp.MainWindow" ...>
<Grid>
<view:UserControl_1/>
<view:UserControl_2/>
</Grid>
</Window>
UserControl_1.xaml:
<UserControl x:Class="MyApp.views.UserControl_1 ...>
<Grid>
<ListView x:Name="MyListView" />
</Grid>
</UserControl>
UserControl_2.xaml
<UserControl x:Class="MyApp.views.UserControl_2 ...>
<Grid>
<Button Content="Test"
Command="TestCommand"
CommandParameter="{Binding Path=MyListView.SelectedIndex,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl_1}}}"
</Grid>
</UserControl>
答案 0 :(得分:1)
创建一个视图模型类,并将其设置为父窗口的DataContext
:
public class ViewModel
{
private int _selectedIndex;
public int SelectedIndex
{
get { return _selectedIndex; }
set { _selectedIndex = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
<强> MainWindow.xaml:强>
<Window x:Class="MyApp.MainWindow" ...>
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Grid>
<view:UserControl_1/>
<view:UserControl_2/>
</Grid>
</Window>
然后,您可以将用户控件中的ListView
和Button
绑定到同一源属性。
<强> UserControl_1.xaml:强>
<UserControl x:Class="MyApp.views.UserControl_1 ...>
<Grid>
<ListView x:Name="MyListView" SelectedIndex="{Binding DataContext.SelectedIndex, RelativeSource={RelativeSource AncestorType=Window}}" />
</Grid>
</UserControl>
<强> UserControl_2.xaml:强>
<UserControl x:Class="MyApp.views.UserControl_2 ...>
<Grid>
<Button Content="Test"
Command="TestCommand"
CommandParameter="{Binding Path=DataContext.SelectedIndex,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" />
</Grid>
</UserControl>