从另一个usercontrol

时间:2017-09-07 02:05:45

标签: wpf mvvm binding

由于原点MainWindow.xaml太大,真的很难维护。所以我将它们分成几个用户控件。但是我遇到了以下问题,UserControl_2中的一个控件引用了ListCon在UserControl_1中的选择。我试图改变绑定,但没有一个按预期工作。知道如何正确绑定到另一个用户控件吗?

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>

1 个答案:

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

然后,您可以将用户控件中的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>