C#在两个页面WPF MVVM之间传递数据

时间:2017-01-10 13:09:27

标签: c# wpf xaml mvvm datagridview

我正在开发一个小型的wpf项目来更好地理解c#和mvvm。 我目前有一个问题,我不知道如何在两个页面之间传递数据。 我想做的事: 我有两页,它们是我的MainWindow的内容。 在PageViewCustomers我有一个DatagridView(有两个,但我只需要一个用于此任务),当我双击一行时,我打开PageAddStaticIPAddress。现在我希望能够访问我在PageAddStaticIPAddress中的PageViewCustomers中双击的行。我想过将所选行作为CommandParameter传递给PageViewCustomers的xaml。 但现在我不知道如何从PageAddStaticIPAddress访问它.. 我已经看到了一些解决方案,但它们都通过在视图中使用Code来解决它。我尝试尽可能减少视图中的代码,并仅使用Bindings,命令和我的视图模型来解决它。

这是我目前的代码:

PageViewCustomers.xaml

<Page x:Class="StaticIPConfiger.PageViewCustomers"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:StaticIPConfiger"
  xmlns:localvm="clr-namespace:StaticIPConfiger.Modelle" 
  xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="500"
  Title="Kundenübersicht">
<Page.DataContext>
    <localvm:VModel />
</Page.DataContext>

<Grid DataContext="{Binding}" >
    <DataGrid IsReadOnly="True"  Name="dgCustomers" ItemsSource="{Binding AlleKunden}" AutoGenerateColumns="False" Margin="0,0,0,197">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Path=c_name}" Width="*"></DataGridTextColumn>
            <DataGridTextColumn Header="Standort" Binding="{Binding Path=l_name}" Width="*"></DataGridTextColumn>
        </DataGrid.Columns>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding UpdateLocations}"
                CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=SelectedItem}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </DataGrid>
    <DataGrid IsReadOnly="True" Name="dg2Customers" ItemsSource="{Binding AlleStandorte}" AutoGenerateColumns="False" Margin="0,168,0,10" >
        <DataGrid.InputBindings>
            <MouseBinding Gesture="LeftDoubleClick" Command="{Binding OpenAddNewIPAddress}"
                          CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=SelectedItem}"/>
        </DataGrid.InputBindings>
        <DataGrid.Columns>
            <DataGridTextColumn Header="StandortId" Binding="{Binding Path=l_id}" Width="*"></DataGridTextColumn>
            <DataGridTextColumn Header="Standort" Binding="{Binding Path=l_name}" Width="*"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

类VModel.cs(PageViewCustomers的VModel)

namespace StaticIPConfiger.Modelle {

public class VModel : INotifyPropertyChanged {
    DataView _alleKunden;
    public VModel()  {
        DataTable dt = new DataTable();
        using (SqlConnection connection = new SqlConnection("Data Source=.\\WERBASWEB;Initial Catalog=customer;Persist Security Info=True;User ID=sa;Password=Dotnet123!")) {
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = new SqlCommand("Select c_id,c_name, l_id,l_name, a_town, a_pcode, a_street from dbo.[AllCustomers]", connection);
            adapter.Fill(dt);
        }
        AlleKunden = dt.DefaultView;
        AlleStandorte = null;

    }

    public DataView AlleKunden { get; private set; }

    public DataView AlleStandorte { get { return _alleKunden; } private set { _alleKunden = value;
            RaisePropertyChanged("AlleStandorte");
        } }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion

    #region Methods

    private void RaisePropertyChanged(string propertyName) {
        // take a copy to prevent thread issues
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion

    #region Commands
    void UpdateLocationView(object parameter) {
        DataRowView selectedRow = (DataRowView)parameter;
        string customerid = selectedRow.Row[0].ToString();
        string locationid = selectedRow.Row[2].ToString();
        DataTable dt = SelectStatements.SelectLocationsForCustomer(locationid,customerid);
        AlleStandorte = dt.DefaultView;
        Console.WriteLine("Test");
    }

    bool CanUpdateLocationView(object parameter) {
        return true;
    }

    public ICommand UpdateLocations { get { return new RelayCommand<object>(param => this.UpdateLocationView(param), param => this.CanUpdateLocationView(param)); } }

    void OpenIPAddress() {
        System.Windows.Application.Current.MainWindow.Content = new AddStaticIPAddress();
    }

    bool CanOpenIPAddress() {
        return true;
    }
    public ICommand OpenAddNewIPAddress {  get { return new RelayCommand(OpenIPAddress,CanOpenIPAddress); } }
    #endregion
}

Page AddStaticIPAddress:

<Page x:Class="StaticIPConfiger.AddStaticIPAddress"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:StaticIPConfiger"
  mc:Ignorable="d" 
  d:DesignHeight="300" d:DesignWidth="500"
  Title="AddStaticIPAddress">

<Page.DataContext>
    <local:AddCustomerVModel/>
</Page.DataContext>
<Grid>
    <Label x:Name="lbl_net" Content="Netz:" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
    <Label x:Name="lbl_subnetmask" Content="Subetnmaske:" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10,36,0,0"/>
    <Label x:Name="label_ipaddress" Content="IP Addresse:" HorizontalAlignment="Left" Margin="10,62,0,0" VerticalAlignment="Top"/>
    <TextBox x:Name="text_net"  Text="" HorizontalAlignment="Left" Height="23" Margin="103,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="text_subetnmask" Text="" HorizontalAlignment="Left"  Height="23" Margin="103,36,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox x:Name="text_ipaddress" Text="" HorizontalAlignment="Left" Height="23" Margin="103,62,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Label x:Name="lbl_description" Content="Bezeichnung:" HorizontalAlignment="Left" Margin="10,85,0,0" VerticalAlignment="Top"/>
    <TextBox x:Name="text_description" Text="" HorizontalAlignment="Left" Height="23" Margin="103,88,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Button x:Name="btn_save_add_ip" Content="IP Addresse hinzufügen" Command ="" HorizontalAlignment="Left" Margin="10,129,0,0" VerticalAlignment="Top" Width="133"/>
    <Button x:Name="btn_abort_add_ip" Content="Verwerfen" HorizontalAlignment="Left" Margin="148,129,0,0" VerticalAlignment="Top" Width="75"/>     
</Grid>

AddIPAddressVModel:

namespace StaticIPConfiger.Modelle {
    class AddIPAddressVModel : INotifyPropertyChanged {
    IPAddress _ipaddress;

    public AddIPAddressVModel() {
        _ipaddress = new IPAddress { Net = "", Subetnmask = "", IpAddress = ""};
    }


    public IPAddress IPAddress {
        get { return _ipaddress; }
        set { _ipaddress = value; }
    }
    #region"Get/Set"
    public int Id {
        get { return IPAddress.Id; }
        set {
            IPAddress.Id = value;
            RaisePropertyChanged("IPAddress");
        }
    }

    public String Net {
        get { return IPAddress.Net; }
        set {
            IPAddress.Net= value;
            RaisePropertyChanged("Net");
        }
    }

    public string Subnetmask {
        get { return IPAddress.Subetnmask; }
        set {
            IPAddress.Subetnmask = value;
            RaisePropertyChanged("Subetnmask");
        }
    }

    public string IpAddress {
        get { return IPAddress.IpAddress; }
        set {
            IPAddress.IpAddress = value;
            RaisePropertyChanged("IPAddress");
        }
    }
    #endregion

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion

    #region Methods

    private void RaisePropertyChanged(string propertyName) {
        // take a copy to prevent thread issues
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}

我希望你理解我的问题;-) 如果您有任何疑问,请告诉我。 谢谢!

编辑: 我如何打开AddIPAddress 我确实将一个Command绑定到DataGrid,我有一个Command OpenAddNewIPAddress:

<DataGrid.InputBindings>
        <MouseBinding Gesture="LeftDoubleClick" Command="{Binding OpenAddNewIPAddress}"
                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=SelectedItem}"/>
</DataGrid.InputBindings>

命令如下所示:

 void OpenIPAddress() {
    System.Windows.Application.Current.MainWindow.Content = new AddStaticIPAddress();
}

bool CanOpenIPAddress() {
    return true;
}
public ICommand OpenAddNewIPAddress {  get { return new RelayCommand(OpenIPAddress,CanOpenIPAddress); } }

我有另一个问题。当我用新的页面设置我的MainWindow(System.Windows.Application.Current.MainWindow.Content = new AddStaticIPAddress();)的内容时,菜单栏会丢失...有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用command参数注入AddIPAddressVModel。像这样:

<DataGrid IsReadOnly="True" Name="dg2Customers" ItemsSource="{Binding AlleStandorte}" AutoGenerateColumns="False" Margin="0,168,0,10" >
    <DataGrid.InputBindings>
        <MouseBinding Gesture="LeftDoubleClick" Command="{Binding OpenAddNewIPAddress}"CommandParameter="{Binding SelectedItem}"/>
    </DataGrid.InputBindings>
    <DataGrid.Columns>
        <DataGridTextColumn Header="StandortId" Binding="{Binding Path=l_id}" Width="*"></DataGridTextColumn>
        <DataGridTextColumn Header="Standort" Binding="{Binding Path=l_name}" Width="*"></DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>
void OpenIPAddress(object parameter)
{
    System.Windows.Application.Current.MainWindow.DataContext  = new AddIPAddressVModel(parameter as DataRowView)
    System.Windows.Application.Current.MainWindow.Content = new AddStaticIPAddress();
}

bool CanOpenIPAddress(object parameter)
{
    return true;
}

public ICommand OpenAddNewIPAddress { get { return new RelayCommand<object>(OpenIPAddress, CanOpenIPAddress); } }
public AddIPAddressVModel(DataRowView drv) {
    _ipaddress = new IPAddress { Net = "", Subetnmask = "", IpAddress = ""};
    _drv = drv; //keep a reference to the clicked DataRowView
}

从AddStaticIPAddress视图中删除它:

<Page.DataContext>
    <local:AddCustomerVModel/>
</Page.DataContext>

Page应继承其DataContext。在XAML标记中设置DataContext仅在视图模型没有依赖项的非常简单的情况下才有用。

答案 1 :(得分:0)

尝试在AddStaticIPAddress中添加字段:

public DataGridRow Row { get; set; }

因此,您可以从VModel访问它。 例如。您可以在AddIPAddressVModel操作上初始化DataGridSelectionChanged

private void dgCustomers_OnSelectionChanged(...)
{
    AddIPAddressVModel addip = new AddIPAddressVModel();
    addip.Row = (DataGridRow) dgCustomers.SelectedItem;
    addip.Show();
}
相关问题