2017-09-07 5 views
0

元のMainWindow.xamlのサイズが大きすぎるため、管理が困難です。そこでそれらを複数のユーザーコントロールに分けます。しかし、次の問題が発生しました.UserControl_2の1つのコントロールは、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で使用する特定のモデル/ビューモデル用に設計する必要があります(Personの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> 
関連する問題