2017-09-07 119 views
0

由于MainWindow.xaml的来源太大,确实难以维护。所以我将它们分成几个用户控件。但是我遇到了以下问题,UserControl_2中的一个控件引用了UserControl_1中的ListView的选择。我试图改变绑定,但没有一个按预期工作。任何想法如何正确绑定到另一个用户控件?从另一个用户控件的自定义用户控件中绑定到内置控件的属性

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

可能是一个更简洁的方法来保持列表中,并且一起引用它在同一用户的控制按钮。 – CodexNZ

+1

声明UserControl_1中的SelectedIndex依赖项属性和UserControl_2中的CommandParameter依赖项属性。通过RelativeSource绑定(在它们各自的XAML中)将它们绑定到相应的UI元素。在MainWindow中,将UserControl_2.CommandParameter绑定到UserControl_1.SelectedIndex。 – Clemens

+0

你的问题来自于你的设计很差。 UserControls应该包含UI的可重用位,并且应该像任何其他控件一样设计(例如,TextBox具有可以绑定到的Text属性),或者设计用于DataTemplating中使用的特定模型/视图模型(例如PersonEditor )。不要使用UserControls将UI切片为更小的块。正如你所发现的那样,这些切片可能会引起关注并阻碍凝聚力。 – Will

回答

0

创建视图模型类,并设置这一个为一体的所述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> 

然后可以绑定在用户控制ListViewButton到相同的源属性。

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> 
相关问题