返回到同一页之后,不再选择“数据网格”的SelectedRow [英] SelectedRow of datagrid is not selected again after returning to same Page

查看:288
本文介绍了返回到同一页之后,不再选择“数据网格”的SelectedRow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的页面选择和编辑。两者共享相同的ViewModel名为SalesAccountsViewModel。



我在选择页面中有一个DataGrid,如下所示:



img src =https://i.stack.imgur.com/la8H9.jpgalt =enter image description here>



然后我选择它任何项目来自DataGrid:





然后我点击选定行上的编辑按钮,如下所示:





之后,我被重定向到另一个页面,如下所示: / p>



当我点击保存按钮时:





我再次被重定向到上一页,但可以看到第一行吗?它没有被突出显示:





以下是我使用的选择页面:

 页面x:Class =MiniAccountWPF.Views.Pages.Masters.SalesAccounts.Select
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:vm =clr-namespace:MiniAccountWPF.ViewModels.Masters
mc:Ignorable =d
d:DesignHeight =300d:DesignWidth =300
标题=选择DataContext ={StaticResource salesAccountsViewModel}>

< Grid>

< Grid.RowDefinitions>
< RowDefinition Height =Auto/>
< RowDefinition Height =*/>
< RowDefinition Height =Auto/>
< /Grid.RowDefinitions>

< Button Grid.Row =0Margin =0,10Horizo​​ntalAlignment =Left
Content ={Binding SelectedChildMenuItem.MenuItemName,Converter = {StaticResource createButtonContentConverter} Source = {StaticResource mainWindowViewModel}}/>

< DataGrid Grid.Row =1ItemsSource ={Binding Ledgers}SelectedValue ={Binding SelectedLedger}
IsReadOnly =TrueAutoGenerateColumns =FalseSelectionMode = SingleSelectionUnit =FullRow>
< DataGrid.Columns>
< DataGridTextColumn Header =客户名称Binding ={Binding LedgerName}/>
< DataGridTextColumn Header =CityBinding ={Binding City}/>
< DataGridTemplateColumn Header =Mobile Numbers>
< DataGridTemplateColumn.CellTemplate>
< DataTemplate>
< TextBlock>
< Run Text ={Binding MobileNo1,Converter = {StaticResource mobileNumberFormatConverter},ConverterParameter = N}/>
< Run Text ={Binding MobileNo1,Converter = {StaticResource mobileNumberFormatConverter},ConverterParameter = S}FontFamily =Consolas/>
< Run Text =FontFamily =Consolas/>
< Run Text ={Binding MobileNo2,Converter = {StaticResource mobileNumberFormatConverter},ConverterParameter = N}/>
< Run Text ={Binding MobileNo2,Converter = {StaticResource mobileNumberFormatConverter},ConverterParameter = S}FontFamily =Consolas/>
< / TextBlock>
< / DataTemplate>
< /DataGridTemplateColumn.CellTemplate>
< / DataGridTemplateColumn>
< DataGridTextColumn Header =期初余额Binding ={Binding OpeningBalance}/>
< DataGridTemplateColumn标题=编辑>
< DataGridTemplateColumn.CellTemplate>
< DataTemplate>
< Button Content =EditStyle ={StaticResource EditButton}
Command ={Binding DataContext.EditCommand,RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = {x:Type Page}} }/>
< / DataTemplate>
< /DataGridTemplateColumn.CellTemplate>
< / DataGridTemplateColumn>
< DataGridTemplateColumn标题=删除>
< DataGridTemplateColumn.CellTemplate>
< DataTemplate>
< Button Content =DeleteStyle ={StaticResource DeleteButton}/>
< / DataTemplate>
< /DataGridTemplateColumn.CellTemplate>
< / DataGridTemplateColumn>
< /DataGrid.Columns>
< / DataGrid>

< / Grid>

< / Page>

这是编辑页面:

 < Page x:Class =MiniAccountWPF.Views.Pages.Masters.SalesAccounts.Edit
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-兼容性/ 2006
xmlns:d =http://schemas.microsoft.com/expression/blend/2008
xmlns:vm =clr-namespace:MiniAccountWPF.ViewModels.Masters
mc:Ignorable =d
d:DesignHeight =300d:DesignWidth =300
标题=编辑DataContext ={StaticResource salesAccountsViewModel}>

< Grid DataContext ={Binding SelectedLedger}>
< Grid.RowDefinitions>
< RowDefinition Height =40/>
< RowDefinition Height =Auto/>
< RowDefinition Height =10/>
< RowDefinition Height =Auto/>
< RowDefinition Height =10/>
< RowDefinition Height =Auto/>
< RowDefinition Height =10/>
< RowDefinition Height =Auto/>
< RowDefinition Height =10/>
< RowDefinition Height =30/>
< RowDefinition Height =Auto/>
< RowDefinition Height =Auto/>
< /Grid.RowDefinitions>

< Grid.ColumnDefinitions>
< ColumnDefinition Width =50/>
< ColumnDefinition Width =Auto/>
< ColumnDefinition Width =*/>
< ColumnDefinition Width =20/>
< ColumnDefinition Width =*/>
< ColumnDefinition Width =350/>
< /Grid.ColumnDefinitions>

< TextBlock Grid.Row =1Grid.Column =1Text =NameStyle ={StaticResource txtBlock}/>
< TextBlock Grid.Row =1Grid.Column =1Text =:Horizo​​ntalAlignment =RightStyle ={StaticResource txtBlock}/>
< TextBox Grid.Row =1Grid.Column =2Grid.ColumnSpan =3Text ={Binding LedgerName}/>

< TextBlock Grid.Row =3Grid.Column =1Text =CityStyle ={StaticResource txtBlock}/>
< TextBlock Grid.Row =3Grid.Column =1Text =:Horizo​​ntalAlignment =RightStyle ={StaticResource txtBlock}/>
< TextBox Grid.Row =3Grid.Column =2Text ={Binding City}/>

< TextBlock Grid.Row =5Grid.Column =1Text =Mobile No. Style ={StaticResource txtBlock}/>
< TextBlock Grid.Row =5Grid.Column =1Text =:Horizo​​ntalAlignment =RightStyle ={StaticResource txtBlock}/>
< TextBox Grid.Row =5Grid.Column =2Text ={Binding MobileNo1}/>
< TextBox Grid.Row =5Grid.Column =4Text ={Binding MobileNo2}/>

< TextBlock Grid.Row =7Grid.Column =1Text =Opening BalanceStyle ={StaticResource txtBlock}/>
< TextBlock Grid.Row =7Grid.Column =1Text =:Horizo​​ntalAlignment =RightStyle ={StaticResource txtBlock}/>
< TextBox Grid.Row =7Grid.Column =2Text ={Binding OpeningBalance}/>

< Grid Grid.Row =10Grid.Column =4>
< Grid.ColumnDefinitions>
< ColumnDefinition Width =*/>
< ColumnDefinition Width =Auto/>
< ColumnDefinition Width =10/>
< ColumnDefinition Width =Auto/>
< /Grid.ColumnDefinitions>

< Button Grid.Column =1Content =保存
Command ={Binding DataContext.EditSaveCommand,RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = {x:Type页}}}/>
< Button Grid.Column =3Content =取消Horizo​​ntalAlignment =Left
Command ={Binding DataContext.EditCancelCommand,RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = {x:键入页面}}}/>

< / Grid>

< / Grid>

< / Page>

ViewModel:

 命名空间MiniAccountWPF.ViewModels.Masters 
{
public class SalesAccountsViewModel:ViewModelBase,IModule
{
public SalesAccountsViewModel()
{

SessionViewModel.Instance.ModulesOpen.Add((IModule)this);

using(MiniAccountDBEntities db = new MiniAccountDBEntities())
{
Ledgers = new ObservableCollection< Ledger>(db.Ledgers.Where(x => x.LedgerType.LedgerTypeName ==客户));
}

EditCommand = new RelayCommand(Edit_Click);
EditSaveCommand = new RelayCommand(Edit_Save_Click);
EditCancelCommand = new RelayCommand(Edit_Cancel_Click);
}

〜SalesAccountsViewModel()
{
SessionViewModel.Instance.ModulesOpen.Remove((IModule)this);
}

private ObservableCollection< Ledger> _ledgers;
public ObservableCollection< Ledger> Ledgers
{
get
{
return _ledgers;
}
set
{
_ledgers = value;
OnPropertyChanged(Ledgers);
}
}

private Ledger _selectedLedger;
public Ledger SelectedLedger
{
get
{
return _selectedLedger;
}
set
{
_selectedLedger = value;
OnPropertyChanged(SelectedLedger);
}
}

public ICommand EditCommand {get;组;

private void Edit_Click(object obj)
{
var mainWindowVM = SessionViewModel.GetModuleInstance(MainWindow,MiniAccountWPF.ViewModels.MainWindowViewModel);
((MainWindowViewModel)mainWindowVM).InnerSourcePage =((MainWindowViewModel)mainWindowVM).SelectedChildMenuItem.EditFrameNavigationURL;
}

public ICommand EditSaveCommand {get;组;

private void Edit_Save_Click(object obj)
{
using(MiniAccountDBEntities db = new MiniAccountDBEntities())
{
Ledger分类帐= db.Ledgers .Single(x => x.LedgerID == SelectedLedger.LedgerID);
ledger.LedgerName = SelectedLedger.LedgerName;
ledger.City = SelectedLedger.City;
ledger.MobileNo1 = SelectedLedger.MobileNo1;
ledger.MobileNo2 = SelectedLedger.MobileNo2;
ledger.OpeningBalance = SelectedLedger.OpeningBalance;
db.SaveChanges();

var mainWindowVM = SessionViewModel.GetModuleInstance(MainWindow,MiniAccountWPF.ViewModels.MainWindowViewModel);
((MainWindowViewModel)mainWindowVM).InnerSourcePage =((MainWindowViewModel)mainWindowVM).SelectedChildMenuItem.SelectFrameNavigationURL;
}
}

public ICommand EditCancelCommand {get;组;

private void Edit_Cancel_Click(object obj)
{
var mainWindowVM = SessionViewModel.GetModuleInstance(MainWindow,MiniAccountWPF.ViewModels.MainWindowViewModel);
((MainWindowViewModel)mainWindowVM).InnerSourcePage =((MainWindowViewModel)mainWindowVM).SelectedChildMenuItem.SelectFrameNavigationURL;
}

public string ModuleFriendlyName
{
get {returnSalesAccountsViewModel; }
}

public string ModuleName
{
get {returnSalesAccounts; }
}
}
}

适用于DataGrid的样式ResourceDictionary:

 < Style TargetType ={x:Type DataGrid}> 
< Setter Property =GridLinesVisibilityValue =Vertical/>
< Setter Property =RowHeaderWidthValue =0/>
< / Style>

< Style TargetType ={x:Type DataGridColumnHeader}>
< Setter Property =BackgroundValue ={StaticResource BrushHeaderBackground}/>
< Setter Property =ForegroundValue =White/>
< Setter Property =PaddingValue =10/>
< Setter Property =FontSizeValue =16/>
< Setter Property =FontWeightValue =SemiBold/>
< Setter Property =Horizo​​ntalContentAlignmentValue =Center/>
< Setter Property =BorderBrushValue =White/>
< Setter Property =BorderThicknessValue =1,0/>

< Style.Triggers>
< MultiTrigger>
< MultiTrigger.Conditions>
< Condition Property =IsMouseOverValue =True/>
< Condition Property =CanUserSortValue =True/>
< /MultiTrigger.Conditions>
< MultiTrigger.Setters>
< Setter Property =BackgroundValue ={StaticResource BrushOrangeSelector}/>
< /MultiTrigger.Setters>
< / MultiTrigger>
< MultiTrigger>
< MultiTrigger.Conditions>
< Condition Property =IsPressedValue =True/>
< Condition Property =CanUserSortValue =True/>
< /MultiTrigger.Conditions>
< MultiTrigger.Setters>
< Setter Property =BackgroundValue ={StaticResource BrushBlueSelector}/>
< /MultiTrigger.Setters>
< / MultiTrigger>
< /Style.Triggers>
< / Style>

< Style TargetType ={x:Type DataGridCell}>

< Setter属性=模板>
< Setter.Value>
< ControlTemplate TargetType ={x:Type DataGridCell}>
< Grid Background ={TemplateBinding Background}>
< ContentPresenter VerticalAlignment =CenterHorizo​​ntalAlignment =Center/>
< / Grid>
< / ControlTemplate>
< /Setter.Value>
< / Setter>

< Setter Property =BackgroundValue =Gray/>
< Setter Property =ForegroundValue =White/>
< Setter Property =PaddingValue =10/>
< Setter Property =FontSizeValue =16/>

< Style.Triggers>
< Trigger Property =IsSelectedValue =True>
< Setter Property =BackgroundValue ={StaticResource BrushBlueSelector}/>
< / Trigger>
< /Style.Triggers>

< / Style>

< Style TargetType ='{x:Type DataGridRow}'>
< Setter Property =BackgroundValue =Gray/>
< Setter Property =Horizo​​ntalContentAlignmentValue =Center/>
< Style.Triggers>
< Trigger Property =IsSelectedValue =True>
< Setter Property =BackgroundValue ={StaticResource BrushBlueSelector}/>
< / Trigger>
< /Style.Triggers>
< / Style>


解决方案

问题是视图模型,每个视图,导致人事收藏的多个副本



所以我确实为单实例在ServiceLocator中为虚拟机添加了一个属性,并初始化了相同的

  public ListViewModel ListViewModel {get; set;} 

然后我从列表视图中替换视图模型的声明,以指向此属性

  DataContext ={Binding ListViewModel,Source = {x:Static vm:ServiceLocator.Instance}}

这解决了集合的多个实例的问题,但是再次datagrid有一些问题重做选择,所以我添加了一个datatrigger的样式重新应用选择

 < DataGrid.RowStyle> 
< Style TargetType =DataGridRow>
< Style.Triggers>
< Trigger Property =IsSelected
Value =true>
< Setter Property =Background
Value ={DynamicResource {x:Static SystemColors.HighlightBrushKey}}/>
< Setter Property =Foreground
Value ={DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}/>
< / Trigger>
< /Style.Triggers>
< / Style>
< /DataGrid.RowStyle>

此触发器将确保即使重新加载该页面也会选择行。



这里是工作示例






编辑



这里是一个解决方案在将ListView中DataGrid中的Metro.xaml



remove DataGrid.RowStyle 在Metro.xaml中,这些

 < Style TargetType ={x:Type DataGridCell}> 
< Setter Property =Template>
< Setter.Value>
< ControlTemplate TargetType ={x:Type DataGridCell}>
< ContentPresenter VerticalAlignment =CenterHorizo​​ntalAlignment =Center/>
< / ControlTemplate>
< /Setter.Value>
< / Setter>
< Setter Property =FontSizeValue =16/>
< Style.Triggers>
< Trigger Property =IsSelectedValue =True>
< Setter Property =ForegroundValue =Black/>
< / Trigger>
< /Style.Triggers>
< / Style>

< Style TargetType ='{x:Type DataGridRow}'>
< Setter Property =TextElement.ForegroundValue =White/>
< Setter Property =BackgroundValue =Gray/>
< Setter Property =HeightValue =50/>
< Setter Property =Horizo​​ntalContentAlignmentValue =Center/>
< Style.Triggers>
< Trigger Property =IsSelectedValue =True>
< Setter Property =BackgroundValue =#FFE1AF4D/>
< Setter Property =TextElement.ForegroundValue =Black/>
< / Trigger>
< /Style.Triggers>
< / Style>


I have two different Pages called Select and Edit. Both of them shares same ViewModel named SalesAccountsViewModel.

I have a DataGrid in Select Page as follows:

Then I select it any Item from the DataGrid :

Then I click on edit button on selected row as shown below:

After that I am redirected to another Page as shown below:

When I click on save button:

I am again redirected to the Previous Page but can you see the first row? It is not Highlighted fully:

Here is Select Page that I use:

<Page x:Class="MiniAccountWPF.Views.Pages.Masters.SalesAccounts.Select"
      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:vm="clr-namespace:MiniAccountWPF.ViewModels.Masters"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="Select" DataContext="{StaticResource salesAccountsViewModel}">

    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Button Grid.Row="0" Margin="0,10" HorizontalAlignment="Left" 
                Content="{Binding SelectedChildMenuItem.MenuItemName, Converter={StaticResource createButtonContentConverter}, Source={StaticResource mainWindowViewModel}}" />

        <DataGrid Grid.Row="1" ItemsSource="{Binding Ledgers}" SelectedValue="{Binding SelectedLedger}" 
                  IsReadOnly="True" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="FullRow">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Customer Name" Binding="{Binding LedgerName}" />
                <DataGridTextColumn Header="City" Binding="{Binding City}" />
                <DataGridTemplateColumn Header="Mobile Numbers">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock>
                                    <Run Text="{Binding MobileNo1, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=N}" />
                                    <Run Text="{Binding MobileNo1, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=S}" FontFamily="Consolas"/>
                                    <Run Text="   " FontFamily="Consolas"/>
                                    <Run Text="{Binding MobileNo2, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=N}" />
                                    <Run Text="{Binding MobileNo2, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=S}" FontFamily="Consolas"/>
                            </TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="Opening Balance" Binding="{Binding OpeningBalance}" />
                <DataGridTemplateColumn Header="Edit">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Edit" Style="{StaticResource EditButton}" 
                                    Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}}}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Delete">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Delete" Style="{StaticResource DeleteButton}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

    </Grid>

</Page>

Here is the Edit Page:

<Page x:Class="MiniAccountWPF.Views.Pages.Masters.SalesAccounts.Edit"
      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:vm="clr-namespace:MiniAccountWPF.ViewModels.Masters"
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
    Title="Edit" DataContext="{StaticResource salesAccountsViewModel}">

    <Grid DataContext="{Binding SelectedLedger}">
        <Grid.RowDefinitions>
            <RowDefinition Height="40" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="10" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="10" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="10" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="10" />
            <RowDefinition Height="30" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="20" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="350" />
        </Grid.ColumnDefinitions>

        <TextBlock Grid.Row="1" Grid.Column="1" Text="Name" Style="{StaticResource txtBlock}"/>
        <TextBlock Grid.Row="1" Grid.Column="1" Text=" : " HorizontalAlignment="Right" Style="{StaticResource txtBlock}"/>
        <TextBox Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="3" Text="{Binding LedgerName}"/>

        <TextBlock Grid.Row="3" Grid.Column="1" Text="City" Style="{StaticResource txtBlock}"/>
        <TextBlock Grid.Row="3" Grid.Column="1" Text=" : " HorizontalAlignment="Right" Style="{StaticResource txtBlock}"/>
        <TextBox Grid.Row="3" Grid.Column="2" Text="{Binding City}"/>

        <TextBlock Grid.Row="5" Grid.Column="1" Text="Mobile No." Style="{StaticResource txtBlock}"/>
        <TextBlock Grid.Row="5" Grid.Column="1" Text=" : " HorizontalAlignment="Right" Style="{StaticResource txtBlock}"/>
        <TextBox Grid.Row="5" Grid.Column="2" Text="{Binding MobileNo1}"/>
        <TextBox Grid.Row="5" Grid.Column="4" Text="{Binding MobileNo2}"/>

        <TextBlock Grid.Row="7" Grid.Column="1" Text="Opening Balance    " Style="{StaticResource txtBlock}"/>
        <TextBlock Grid.Row="7" Grid.Column="1" Text=" : " HorizontalAlignment="Right" Style="{StaticResource txtBlock}"/>
        <TextBox Grid.Row="7" Grid.Column="2" Text="{Binding OpeningBalance}"/>

        <Grid Grid.Row="10" Grid.Column="4">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="10" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>

            <Button Grid.Column="1" Content="Save" 
                    Command="{Binding DataContext.EditSaveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}}}"/>
            <Button Grid.Column="3" Content="Cancel" HorizontalAlignment="Left" 
                    Command="{Binding DataContext.EditCancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}}}"/>

        </Grid>

    </Grid>

</Page>

The ViewModel:

namespace MiniAccountWPF.ViewModels.Masters
{
    public class SalesAccountsViewModel: ViewModelBase, IModule
    {
        public SalesAccountsViewModel()
        {

            SessionViewModel.Instance.ModulesOpen.Add((IModule)this);

            using (MiniAccountDBEntities db = new MiniAccountDBEntities())
            {
                Ledgers = new ObservableCollection<Ledger>(db.Ledgers.Where(x => x.LedgerType.LedgerTypeName == "Customer"));
            }

            EditCommand = new RelayCommand(Edit_Click);
            EditSaveCommand = new RelayCommand(Edit_Save_Click);
            EditCancelCommand = new RelayCommand(Edit_Cancel_Click);
        }

        ~SalesAccountsViewModel()
        {
            SessionViewModel.Instance.ModulesOpen.Remove((IModule)this);
        }

        private ObservableCollection<Ledger> _ledgers;
        public ObservableCollection<Ledger> Ledgers
        {
            get
            {
                return _ledgers;
            }
            set
            {
                _ledgers = value;
                OnPropertyChanged("Ledgers");
            }
        }

        private Ledger _selectedLedger;
        public Ledger SelectedLedger
        {
            get
            {
                return _selectedLedger;
            }
            set
            {
                _selectedLedger = value;
                OnPropertyChanged("SelectedLedger");
            }
        }

        public ICommand EditCommand { get; set; }

        private void Edit_Click(object obj)
        {
            var mainWindowVM = SessionViewModel.GetModuleInstance("MainWindow", "MiniAccountWPF.ViewModels.MainWindowViewModel");
            ((MainWindowViewModel)mainWindowVM).InnerSourcePage = ((MainWindowViewModel)mainWindowVM).SelectedChildMenuItem.EditFrameNavigationURL;
        }

        public ICommand EditSaveCommand { get; set; }

        private void Edit_Save_Click(object obj)
        {
            using (MiniAccountDBEntities db = new MiniAccountDBEntities())
            {
                Ledger ledger = db.Ledgers.Single(x => x.LedgerID == SelectedLedger.LedgerID);
                ledger.LedgerName = SelectedLedger.LedgerName;
                ledger.City = SelectedLedger.City;
                ledger.MobileNo1 = SelectedLedger.MobileNo1;
                ledger.MobileNo2 = SelectedLedger.MobileNo2;
                ledger.OpeningBalance = SelectedLedger.OpeningBalance;
                db.SaveChanges();

                var mainWindowVM = SessionViewModel.GetModuleInstance("MainWindow", "MiniAccountWPF.ViewModels.MainWindowViewModel");
                ((MainWindowViewModel)mainWindowVM).InnerSourcePage = ((MainWindowViewModel)mainWindowVM).SelectedChildMenuItem.SelectFrameNavigationURL;
            }
        }

        public ICommand EditCancelCommand { get; set; }

        private void Edit_Cancel_Click(object obj)
        {
                var mainWindowVM = SessionViewModel.GetModuleInstance("MainWindow", "MiniAccountWPF.ViewModels.MainWindowViewModel");
                ((MainWindowViewModel)mainWindowVM).InnerSourcePage = ((MainWindowViewModel)mainWindowVM).SelectedChildMenuItem.SelectFrameNavigationURL;
        }

        public string ModuleFriendlyName
        {
            get { return "SalesAccountsViewModel"; }
        }

        public string ModuleName
        {
            get { return "SalesAccounts"; }
        }
    }
}

Styles applied to DataGrid in ResourceDictionary:

<Style TargetType="{x:Type DataGrid}">
    <Setter Property="GridLinesVisibility" Value="Vertical" />
    <Setter Property="RowHeaderWidth" Value="0" />
</Style>

<Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Background" Value="{StaticResource BrushHeaderBackground}" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Padding" Value="10" />
    <Setter Property="FontSize" Value="16" />
    <Setter Property="FontWeight" Value="SemiBold" />
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="BorderBrush" Value="White" />
    <Setter Property="BorderThickness" Value="1,0" />

    <Style.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsMouseOver" Value="True" />
                <Condition Property="CanUserSort" Value="True" />
            </MultiTrigger.Conditions>
            <MultiTrigger.Setters>
                <Setter Property="Background" Value="{StaticResource BrushOrangeSelector}" />
            </MultiTrigger.Setters>
        </MultiTrigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsPressed" Value="True" />
                <Condition Property="CanUserSort" Value="True" />
            </MultiTrigger.Conditions>
            <MultiTrigger.Setters>
                <Setter Property="Background" Value="{StaticResource BrushBlueSelector}" />
            </MultiTrigger.Setters>
        </MultiTrigger>
    </Style.Triggers>
</Style>

<Style TargetType="{x:Type DataGridCell}">

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>

    <Setter Property="Background" Value="Gray" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Padding" Value="10" />
    <Setter Property="FontSize" Value="16" />

    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="{StaticResource BrushBlueSelector}" />
        </Trigger>
    </Style.Triggers>

</Style>

<Style TargetType='{x:Type DataGridRow}'>
    <Setter Property="Background" Value="Gray" />
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="{StaticResource BrushBlueSelector}" />
        </Trigger>
    </Style.Triggers>
</Style>

解决方案

the issue was view model, which was getting created with every view, leading to multiple copies of person collection

so I did place a property for VM in ServiceLocator for single instance and initialized the same

public ListViewModel ListViewModel {get; set;}

then I replaced the declaration of view model from the list view to point to this property

DataContext="{Binding ListViewModel, Source={x:Static vm:ServiceLocator.Instance}}"

this solves the problem of multiple instance of the collection but again datagrid has some problem redoing the selection so I added a style with datatrigger to reapply the selection

    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <Trigger Property="IsSelected"
                         Value="true">
                    <Setter Property="Background"
                            Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
                    <Setter Property="Foreground"
                            Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>

this trigger will ensure the row looks selected even if the page is reloaded.

here is a working sample


EDIT

here is a solution for the issue after merging Metro.xaml

remove DataGrid.RowStyle from the DataGrid in ListView and replace the mentioned styles in Metro.xaml with these

<Style TargetType="{x:Type DataGridCell}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="FontSize" Value="16" />
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="Black" />
        </Trigger>
    </Style.Triggers>
</Style>

<Style TargetType='{x:Type DataGridRow}'>
    <Setter Property="TextElement.Foreground" Value="White" />
    <Setter Property="Background" Value="Gray" />
    <Setter Property="Height" Value="50" />
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="#FFE1AF4D" />
            <Setter Property="TextElement.Foreground" Value="Black" />
        </Trigger>
    </Style.Triggers>
</Style>

这篇关于返回到同一页之后,不再选择“数据网格”的SelectedRow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆