I have tried to find a good consistent folder structure in Visual Studio to capture all the possibilities. This so far has been what I've came up with for my project.
My Application looks like:
The xaml is pretty straight forward:
<Window x:Class="Check.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:SA_BOM_Check.ViewModels"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type=viewModels:MainWindowViewModel, IsDesignTimeCreatable=True}"
Height="600" Width="800"
DataContext="{StaticResource ResourceKey=MainWindowViewModel}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="10"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="1" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Right" Text="XA File: " Height="30" FontSize="20" FontWeight="Bold"/>
<TextBox x:Name="TxtXAFile" Grid.Row="1" Grid.Column="1" Text="{Binding Path=XAFile, Mode=TwoWay}" VerticalAlignment="Center" FontSize="15"></TextBox>
<Button x:Name="BtnXaBrowse" Grid.Row="1" Grid.Column="2" VerticalAlignment="Center" Margin="10,5,80,1" FontSize="20" FontWeight="DemiBold" Click="BtnXaBrowse_OnClick">Browse...</Button>
<TextBlock Grid.Row="2" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Right" Text="Inventor File: " Height="30" FontSize="20" FontWeight="Bold"/>
<TextBox Grid.Row="2" Grid.Column="1" x:Name="TxtInventorFile" Text="{Binding Path=InventorFile, Mode=TwoWay}" VerticalAlignment="Center" FontSize="15"/>
<Button x:Name="BtnInventorBrowse" Grid.Row="2" Grid.Column="2" VerticalAlignment="Center" Margin="10,0,80,0" FontSize="20" FontWeight="DemiBold" Click="BtnInventorBrowse_OnClick">Browse...</Button>
<Button x:Name="BtnDiff" Grid.Row="2" Grid.Column="3" VerticalAlignment="Center" Margin="10,5,80,1" FontSize="20" FontWeight="DemiBold" Command="{Binding GetDifferences}">Differences</Button>
<Line Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" X1="0" Y1="0" X2="1" Y2="0" Stroke="Black" StrokeThickness="2" Stretch="Uniform"></Line>
<Label Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="4" Content="Missing in Inventor (Inventor - XA)" FontSize="15" FontStyle="Normal" HorizontalAlignment="Center" FontWeight="Bold" Foreground="Black"/>
<DataGrid AutoGenerateColumns="True" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="4" IsReadOnly="True"
FontSize="18" ItemsSource="{Binding Path=XADiffDataTable}"
ColumnWidth="*">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
</DataGrid>
<Label Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="4"
Content="Missing In XA (XA - Inventor)" FontSize="15" FontStyle="Normal"
HorizontalAlignment="Center" FontWeight="Bold" Foreground="Black"/>
<DataGrid Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="4"
AutoGenerateColumns="True" IsReadOnly="True"
FontSize="18" ItemsSource="{Binding Path=InventorDiffDataTable}"
ColumnWidth="*">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
</DataGrid.ColumnHeaderStyle>
</DataGrid>
</Grid>
</Window>
Code Behind:
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using SA_BOM_Check.ViewModels;
namespace SA_BOM_Check.Views
{
public partial class MainWindow : Window
{
//private readonly MainWindowViewModel _vm;
public MainWindow()
{
InitializeComponent();
//_vm = (MainWindowViewModel) this.DataContext;
}
private void BtnXaBrowse_OnClick(object sender, RoutedEventArgs e)
{
TxtXAFile.Text = OpenFileDialog();
TxtXAFile.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
//_vm.XAFile = OpenFileDialog();
}
private void BtnInventorBrowse_OnClick(object sender, RoutedEventArgs e)
{
TxtInventorFile.Text = OpenFileDialog();
TxtInventorFile.GetBindingExpression((TextBox.TextProperty))?.UpdateSource();
}
private string OpenFileDialog()
{
OpenFileDialog openFileDialog = new();
return openFileDialog.ShowDialog() == true ? openFileDialog.FileName : "";
}
}
}
Keeping the ShowDialog inside the code behind was inspired by BionicCode https://stackoverflow.com/users/3141792/bioniccode
Where he answered the question about OpenFileDialogs Open File Dialog MVVM Actual Answer (which should have been the answer to the question) is at https://stackoverflow.com/a/64861760/4162851
The InventorAndXACompare class in summary is
private static readonly Dictionary<string, Part> INVENTOR_PARTS
= new Dictionary<string, Part>();
private static readonly Dictionary<string, Part> XA_PARTS = new Dictionary<string, Part>();
private static readonly Dictionary<string, Part> XA_PARTS_OMIT = new Dictionary<string, Part>();
private static readonly DataTable MISSING_IN_INVENTOR = new DataTable("XACompared");
private static readonly DataTable MISSING_IN_XA = new DataTable("InventorCompared");
public static DataTable[] CompareFiles(string xaFile, string inventorFile)
private static void ParseInventor(string inventorFile)
private static void ParseXA(string xaFile)
private static void CompareXAToInventor()
private static void CompareInventorToXA()
The compare files takes two files. It then parses those files into two dictionaries that are compared in both directions where there are differences it adds those rows to a datatable inside the MainWindowViewModel those are then binded to the View by
private DataTable _xaDiffDataTable;
public DataTable XADiffDataTable
{
get { return _xaDiffDataTable;}
set
{
_xaDiffDataTable = value;
OnPropertyChanged("XADiffDataTable");
}
}
private DataTable _inventorDiffDataTable;
public DataTable InventorDiffDataTable
{
get { return _inventorDiffDataTable;}
set
{
_inventorDiffDataTable = value;
OnPropertyChanged("InventorDiffDataTable");
}
}
I would like to know if there is a better way of structuring this and if InventorAndXACompare would be better placed in the Models folder?
In an MVVM architecture you would usually find parsers in the Model component. The View Model generally does not process data. Usually it may convert data to meet the constraints of the Model's interface or to prepare data for presentation in the View.
Also from an MVVM point of view the data source and sink is always part of the Model. It does not matter whether data comes from a database or from a file picked by the user.
Related
I have viewlist in which contain elements. When I click on them, my ItemViewModel handler clicks. Then I can select information about that element. Afthe I must to open new page in which will be all information about it. For example like hypertext in browser.
<Border MaxHeight="300" MaxWidth="1140" CornerRadius="25" Margin="73,269,65,182">
<Grid x:Name="MainGrid" RenderTransformOrigin="0.5,0.5" Margin="0,0,10,-3">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListView Width="1031" ItemsSource="{Binding GetTopItem}"
ScrollViewer.VerticalScrollBarVisibility="Disabled" HorizontalAlignment="Left" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
Background="{x:Null}" BorderBrush="{x:Null}" Foreground="#DD000000"
x:Name="ListBook">
<ListView.DataContext>
<vm:BookMainVM/>
</ListView.DataContext>
<ListView.ItemTemplate>
<DataTemplate>
<Border HorizontalAlignment="Left" CornerRadius="25,25,25,25" BorderThickness="1" BorderBrush="#FF474747" Height="288" Margin="0,0,0,0" MouseDown="Border_MouseDown" >
<Grid Grid.Column="0" Height="Auto" Width="216" Margin="-1" IsEnabled="False">
<Grid.InputBindings>
<MouseBinding Gesture="LeftClick"
Command="{Binding DataContext.DelegateCommands,
RelativeSource={RelativeSource AncestorType=ListView}}"
CommandParameter="{Binding}">
</MouseBinding>
</Grid.InputBindings>
<Grid.RowDefinitions>
<RowDefinition Height="49*"/>
<RowDefinition Height="5*"/>
<RowDefinition Height="18*"/>
</Grid.RowDefinitions>
<Border CornerRadius="25,25,0,0" RenderTransformOrigin="0.5,0.5">
<Border.Background>
<ImageBrush ImageSource="{Binding Img_src}" Stretch="Fill" />
</Border.Background>
</Border>
<Label Content="{Binding Rate}" Background="#FFBFBFBF" RenderTransformOrigin="0.5,0.5" Grid.Row="1" FontSize="11" FontFamily="Meiryo UI" HorizontalContentAlignment="Center"/>
<Border CornerRadius="0,0,25,25" Grid.Row="2" Background="#FF8F8F8F">
<TextBlock Margin="6,0,0,0" Text="{Binding Name}" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Grid.Row="2" Height="61" Width="190"/>
</Border>
</Grid>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Border>
class ItemMainVM:ViewModel
{
private LibraryModel libraryModel;
private ItemDb itemsDb;
private const string Dir = "D:\\repos\\Frame\\Frame\\src";
public ItemMainVM()
{
libraryModel = new LibraryModel();
itemsDb = new BooksDb();
DelegateCommands = new DelegateCommand(o => EventHandler(o));
}
public ObservableCollection<BookPreviewInfo> GetTopItem
{
get
{
return libraryModel.GetTopItems();
}
}
public ICommand DelegateCommands { get; }
public void EventHandler(dynamic item)
{
itemDb.SelectItemId(item.Id);
}
}
Code Behind is empty.
When I click an element and executing EventHandler in ItemMainVM. And next must be create new page with new ElementViewModel.
ElementViewModel should to get information about element in ItemMainVM.
I have a problem I can not solve.
As you can see in the picture , there is a label , a textobx and a ScrollViewer .
Now , I have to update the ScrollViewer when the user searches through the textbox .
Part of an event every time you make a keydown .
So if I write Statut ... should put first in the file list with the names "statuto rai"
the list can have N elements
Image list:
Xaml code:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="GhostWhite"/>
<Grid Grid.Row="1" Background="Gray"/>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Documenti allegati</TextBlock>
<Border Grid.Row="1" Margin="3" BorderBrush="White" Height="22" Background="#fff">
<TextBox BorderBrush="#465E76" KeyDown="TextBox_KeyDown" BorderThickness="0" FontSize="10" Background="#fff" Foreground="#565656" controls:TextBoxHelper.Watermark="Ricerca Locale" FontFamily="{StaticResource Lato Thin}" HorizontalContentAlignment="Center" ></TextBox>
</Border>
<ScrollViewer Grid.Row="2" VerticalScrollBarVisibility="Hidden" PanningMode="Both" Name="scrollDocuments">
<ItemsControl ItemsSource="{Binding Path=attachmentsList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Grid.Column="0" Grid.Row="0">
<Button Grid.ColumnSpan="2">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="450"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Background="#fff"></Grid>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="10" Margin="10,3,0,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding contList}"/>
<Image Source="/Resources/Images/icon-document-browser.png" HorizontalAlignment="Left" Margin="22,-12,0,0" Width="22"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="10" Margin="21,32,0,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding FileSizeConverted}"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="12" Margin="55,-10,0,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding Name}"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="12" Margin="55,-10,10,0" Style="{DynamicResource Lato-Semibold}" Text="{Binding ModifiedDate}"/>
<TextBlock Foreground="#565656" FontFamily="{StaticResource Lato Semibold}" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="10" Margin="55,25,10,0" FontWeight="Bold" Style="{DynamicResource Lato-Semibold}" Text="Nessuna copia locale"/>
<Border Grid.Row="0" Grid.ColumnSpan="2" BorderBrush="#DDD" BorderThickness="0,0,0,1"></Border>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<Viewbox Grid.Row="2" Name="testoNessunAllegato" Visibility="Collapsed" Margin="20">
<TextBlock Text="Nessun allegato disponibile."></TextBlock>
</Viewbox>
</Grid>
CodeBehind event code:
private void TextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
string find = ((TextBox)sender).Text;
attachmentsList = attachmentsList.Where(x => x.Name == find).ToList();
InitializeComponent();
}
in practice I do the intelligiente research, so every time I insert a letter filtrale list , and print it again , of course real time .
I hope I explained myself .
Thank you
I see you use bindings, in this case there is a much better stuff to reach your goal. It's CollectionView.
Here is a simple app for you which more or less fullfill your requirements:
View
<StackPanel Orientation="Horizontal">
<Label Content="Search" />
<TextBox MinWidth="30" Text="{Binding FilterText, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
<ListBox ItemsSource="{Binding Data}" />
UpdateSorceTrigger=PropertyChanges updates FilterText in ViewModel every time when you press any key.
Data is a ICollectionView
ViewModel
public ICollectionView Data { get; private set; }
...
// Create default view for the list
Data = CollectionViewSource.GetDefaultView(list);
// Set filter delegate for CollectionView
Data.Filter = FilterData;
....
private bool FilterData(object obj)
{
DataContainer cont = (DataContainer)obj;
return string.IsNullOrEmpty(FilterText) || cont.Name.StartsWith(FilterText, StringComparison.OrdinalIgnoreCase);
}
private string myfiltertext;
public string FilterText
{
get { return myfiltertext; }
set
{
myfiltertext = value;
// Refresh collection view after Filter text modification
Data.Refresh();
}
}
I am trying to create a flipview on the an ItemDetailpage. I am using the default template provided in visual studio when creating a grid app.
Pages in the App: GroupItemsPage, GroupDetailPage, ItemDetailPage
The problem is, I am getting this error when I click on an item on the GroupItemsPage or GroupDetailPage:
Object reference not set to an instance of an object.
Error details:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=AppError
StackTrace: at AppError.ItemDetailPage.<navigationHelper_LoadState>d__0.MoveNext()
This is my code:
GroupItemsPage.xaml
<Page
x:Name="pageRoot"
x:Class="AppError.GroupedItemsPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppError"
xmlns:data="using:AppError.Data"
xmlns:common="using:AppError.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<x:String x:Key="ChevronGlyph"></x:String>
<!--
Collection of grouped items displayed by this page, bound to a subset
of the complete item list because items in groups cannot be virtualized
-->
<CollectionViewSource
x:Name="groupedItemsViewSource"
Source="{Binding Groups}"
IsSourceGrouped="true"
ItemsPath="Items"
d:Source="{Binding Groups, Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"/>
</Page.Resources>
<!--
This grid acts as a root panel for the page that defines two rows:
* Row 0 contains the back button and page title
* Row 1 contains the rest of the page layout
-->
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Horizontal scrolling grid -->
<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Grouped Items"
Grid.RowSpan="2"
Padding="116,137,40,46"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Width="250" Height="250">
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
</Border>
<StackPanel VerticalAlignment="Bottom" Background="{ThemeResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock Text="{Binding Title}" Foreground="{ThemeResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextBlockStyle}" Height="60" Margin="15,0,15,0"/>
<TextBlock Text="{Binding Subtitle}" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid GroupPadding="0,0,70,0"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="0,0,0,2">
<Button Foreground="{ThemeResource ApplicationHeaderForegroundThemeBrush}"
AutomationProperties.Name="Group Title"
Click="Header_Click"
Style="{StaticResource TextBlockButtonStyle}" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Margin="0,-11,10,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
<TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-11,0,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</GridView.GroupStyle>
</GridView>
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
Style="{StaticResource NavigationBackButtonNormalStyle}"
VerticalAlignment="Top"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
</Grid>
</Grid>
GroupItemsPage.xaml.cs
namespace AppError
{
public sealed partial class GroupedItemsPage : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
public GroupedItemsPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
}
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var sampleDataGroups = await SampleDataSource.GetGroupsAsync();
this.DefaultViewModel["Groups"] = sampleDataGroups;
}
void Header_Click(object sender, RoutedEventArgs e)
{
// Determine what group the Button instance represents
var group = (sender as FrameworkElement).DataContext;
// Navigate to the appropriate destination page, configuring the new page
// by passing required information as a navigation parameter
this.Frame.Navigate(typeof(GroupDetailPage), ((SampleDataGroup)group).UniqueId);
}
void ItemView_ItemClick(object sender, ItemClickEventArgs e)
{
// Navigate to the appropriate destination page, configuring the new page
// by passing required information as a navigation parameter
var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
this.Frame.Navigate(typeof(ItemDetailPage), itemId);
}
}
GroupDetailpage.xaml
<Page
x:Name="pageRoot"
x:Class="AppError.GroupDetailPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppError"
xmlns:data="using:AppError.Data"
xmlns:common="using:AppError.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<!-- Collection of items displayed by this page -->
<CollectionViewSource
x:Name="itemsViewSource"
Source="{Binding Items}"
d:Source="{Binding Groups[0].Items, Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"/>
</Page.Resources>
<!--
This grid acts as a root panel for the page that defines two rows:
* Row 0 contains the back button and page title
* Row 1 contains the rest of the page layout
-->
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{Binding Group}"
d:DataContext="{Binding Groups[0], Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Horizontal scrolling grid -->
<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Items In Group"
TabIndex="1"
Grid.RowSpan="2"
Padding="120,126,120,50"
ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="110" Width="480" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="110" Height="110">
<Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
</Border>
<StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Description}" Style="{StaticResource BodyTextBlockStyle}" MaxHeight="60"/>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.Header>
<StackPanel Width="480" Margin="0,4,14,0">
<TextBlock Text="{Binding Subtitle}" Margin="0,0,0,20" Style="{StaticResource SubheaderTextBlockStyle}" MaxHeight="60"/>
<Image Source="{Binding ImagePath}" Height="400" Margin="0,0,0,20" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
<TextBlock Text="{Binding Description}" Margin="0,0,0,0" Style="{StaticResource BodyTextBlockStyle}"/>
</StackPanel>
</GridView.Header>
<GridView.ItemContainerStyle>
<Style TargetType="FrameworkElement">
<Setter Property="Margin" Value="52,0,0,2"/>
</Style>
</GridView.ItemContainerStyle>
</GridView>
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
Style="{StaticResource NavigationBackButtonNormalStyle}"
VerticalAlignment="Top"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="{Binding Title}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
</Grid>
</Grid>
GroupDetailPage.xaml.cs
namespace AppError
{
public sealed partial class GroupDetailPage : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
public GroupDetailPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
}
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var group = await SampleDataSource.GetGroupAsync((String)e.NavigationParameter);
this.DefaultViewModel["Group"] = group;
this.DefaultViewModel["Items"] = group.Items;
}
void ItemView_ItemClick(object sender, ItemClickEventArgs e)
{
// Navigate to the appropriate destination page, configuring the new page
// by passing required information as a navigation parameter
var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
this.Frame.Navigate(typeof(ItemDetailPage), itemId);
}
}
ItemDetailPage.xaml
<Page
x:Name="pageRoot"
x:Class="AppError.ItemDetailPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AppError"
xmlns:data="using:AppError.Data"
xmlns:common="using:AppError.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<CollectionViewSource
x:Name="itemViewSource"
Source="{Binding Items}"
d:Source="{Binding Groups[0].Items, Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"/>
</Page.Resources>
<!--
This grid acts as a root panel for the page that defines two rows:
* Row 0 contains the back button and page title
* Row 1 contains the rest of the page layout
-->
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
DataContext="{Binding Item}"
d:DataContext="{Binding Groups[0].Items[0], Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--
TODO: Content should be placed within the following grid
to show details for the current item
-->
<FlipView
Grid.Row="1"
x:Name="flipView"
Margin="50,0,0,0"
ItemsSource="{Binding Source={StaticResource itemViewSource}}">
<FlipView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="500"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel>
<Border>
<Image Source="{Binding ImagePath}"/>
</Border>
<TextBlock Text="{Binding Description}" Padding="0,30,0,0" TextWrapping="Wrap"/>
</StackPanel>
<Grid Grid.Column="1" Margin="30,0,0,0">
<TextBlock Text="{Binding Content}" TextWrapping="Wrap"/>
</Grid>
</Grid>
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
Style="{StaticResource NavigationBackButtonNormalStyle}"
VerticalAlignment="Top"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="{Binding Title}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
</Grid>
</Grid>
ItemDetailPage.xaml.cs
namespace AppError
{
public sealed partial class ItemDetailPage : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
public ItemDetailPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
}
private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var group = await SampleDataSource.GetGroupAsync((String)e.NavigationParameter);
var item = await SampleDataSource.GetItemAsync((String)e.NavigationParameter);
this.DefaultViewModel["Group"] = group;
this.DefaultViewModel["Items"] = group.Items;
this.flipView.SelectedItem = item;
}
}
xmal code:
<ListBox x:Name="listbox2" Margin="0,0" SelectionChanged="listbox2_SelectionChanged" Hold="listbox2_Hold" >
<ListBox.ItemContainerStyle >
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderThickness="0,0,0,1" BorderBrush="Gray">
<Grid Width="auto" HorizontalAlignment="Stretch" >
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center" FontSize="40" Grid.Column="1" Grid.Row="0" Foreground="White" Text="{Binding NAME}"></TextBlock>
<TextBlock VerticalAlignment="Center" FontSize="25" Grid.Column="1" Grid.Row="1" Foreground="Blue" Text="{Binding PHONE}"></TextBlock>
<Image Name="c1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="100" Height="100" Stretch="Fill" Margin="0" Source="{Binding IMGS}" Grid.RowSpan="2" Grid.Column="0" />
</Grid>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
class list which is bind to list box is
List < contactsclass > contacts = new List < contactsclass >();
PHONE and NAME are getter setter of the contactclass's variables
how can i get this variable's value on hold event of listbox .. i am trying following code
private void listbox2_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
//contextmenucontact = (contactsclass)(sender as ListBox).DataContext;
contextmenucontact = (contactsclass)listbox2.SelectedItem;
MessageBox.Show(contextmenucontact.name);
}
if is just the selected item is just use the ToString Function, see this:
if (listBox1.SelectedItem != null)
{
string itemText = listBox1.SelectedItem.ToString();
contextmenucontact = new contactsclass();
contextmenucontact.name = itemText;
MessageBox.Show(contextmenucontact.name);
}
I have two grids with three rows each. The first and last row of each grid has a fixed height while the middle rows have auto height and share their height using SharedSizeGroup.
First, the content of the right grid determines the height of the size group. When the content of the right grid shrinks so that the content of the left grid determines the height of the size group, the overall size of the left grid is not adjusted correctly.
See the following sample app. Click the increase button to increase the size of the textblock in the right grid. The size of the left grid changes accordingly. Now decrease the size. When the textblock becomes smaller than the textblock in the left grid, the total size of the left grid doesn't shrink. Is this a bug or am i missing something?
<StackPanel Orientation="Horizontal" Grid.IsSharedSizeScope="True">
<StackPanel Orientation="Vertical" Width="100">
<Grid Background="Green">
<Grid.RowDefinitions>
<RowDefinition Height="15" />
<RowDefinition SharedSizeGroup="Group1" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<TextBlock Background="Blue" Grid.Row="0" />
<TextBlock Background="Red" Grid.Row="1" Name="textBlock1" Height="100" />
<TextBlock Background="Blue" Grid.Row="2" />
</Grid>
<TextBlock Text="{Binding Path=ActualHeight, ElementName=grid1}" />
</StackPanel>
<StackPanel Orientation="Vertical" Width="100">
<Grid Background="Green">
<Grid.RowDefinitions>
<RowDefinition Height="15" />
<RowDefinition SharedSizeGroup="Group1" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<TextBlock Background="Blue" Grid.Row="0" />
<TextBlock Background="Red" Grid.Row="1" Name="textBlock2" Height="150" />
<TextBlock Background="Blue" Grid.Row="2" />
</Grid>
<TextBlock Text="{Binding Path=ActualHeight, ElementName=grid2}" />
</StackPanel>
<Button Height="24" Click="Button_Click_1" VerticalAlignment="Top">Increase</Button>
<Button Height="24" Click="Button_Click_2" VerticalAlignment="Top">Decrease</Button>
</StackPanel>
private void Button_Click_1(object sender, RoutedEventArgs e)
{
textBlock2.Height += 30;
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
textBlock2.Height -= 30;
}
The rows are staying the same height - the size of the second TextBlock is changing, while the size of the first TextBlock remains 100.
To demonstrate this, make the following changes:
Add ShowGridLines="True" to each of your Grids
Change your named TextBlocks to show their ActualHeight as their text:
<TextBlock Background="Red" Grid.Row="1" Name="textBlock2" Height="150"
Text="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"/>
You will see that the SharedSizeGroup row will be the maximum ActualHeight of the two TextBlocks.
Update: A Short Project To Show What's Happening
I've created a quick-n-dirty project to show what's happening. It turns out that when the right grid gets smaller than the original size, the left grid does an Arrange but not a Measure. I am not sure I understand this completely - I have posted a follow-up question with this same solution.
Here is the solution that I created, based on your original. It simply wraps the basic grid in a custom class that spews out info (via event) when Measure and Arrange are called. In the main window, I just put that info into a list box.
InfoGrid and InfoGridEventArgs classes
using System.Windows;
using System.Windows.Controls;
namespace GridMeasureExample
{
class InfoGrid : Grid
{
protected override Size ArrangeOverride(Size arrangeSize)
{
CallReportInfoEvent("Arrange");
return base.ArrangeOverride(arrangeSize);
}
protected override Size MeasureOverride(Size constraint)
{
CallReportInfoEvent("Measure");
return base.MeasureOverride(constraint);
}
public event EventHandler<InfoGridEventArgs> ReportInfo;
private void CallReportInfoEvent(string message)
{
if (ReportInfo != null)
ReportInfo(this, new InfoGridEventArgs(message));
}
}
public class InfoGridEventArgs : EventArgs
{
private InfoGridEventArgs()
{
}
public InfoGridEventArgs(string message)
{
this.TimeStamp = DateTime.Now;
this.Message = message;
}
public DateTime TimeStamp
{
get;
private set;
}
public String Message
{
get;
private set;
}
}
}
Main Window XAML
<Window x:Class="GridMeasureExample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GridMeasureExample"
Title="SharedSizeGroup" Height="500" Width="500">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Column="0"
Grid.Row="0"
Orientation="Horizontal"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Grid.IsSharedSizeScope="True">
<StackPanel Orientation="Vertical" Width="100">
<local:InfoGrid x:Name="grid1" Background="Green" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="15" />
<RowDefinition SharedSizeGroup="Group1" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<TextBlock Background="Blue" Grid.Row="0" Text="Row 0"/>
<TextBlock Background="Red" Grid.Row="1" Name="textBlock1" Height="100"
Text="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"/>
<TextBlock Background="Blue" Grid.Row="2" Text="Row 2" />
</local:InfoGrid>
<TextBlock Text="{Binding Path=ActualHeight, ElementName=grid1}" />
</StackPanel>
<StackPanel Orientation="Vertical" Width="100">
<local:InfoGrid x:Name="grid2" Background="Yellow" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="15" />
<RowDefinition SharedSizeGroup="Group1" />
<RowDefinition Height="15" />
</Grid.RowDefinitions>
<TextBlock Background="Orange" Grid.Row="0" Text="Row 0" />
<TextBlock Background="Purple" Grid.Row="1" Name="textBlock2" Height="150"
Text="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"/>
<TextBlock Background="Orange" Grid.Row="2" Text="Row 2" />
</local:InfoGrid>
<TextBlock Text="{Binding Path=ActualHeight, ElementName=grid2}" />
</StackPanel>
</StackPanel>
<ListBox x:Name="lstInfo"
Grid.Column="1"
Grid.Row="0"
Margin="10,0,0,0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
<UniformGrid Grid.Column="0"
Grid.Row="1"
Grid.ColumnSpan="2"
Columns="2"
HorizontalAlignment="Center"
Margin="5">
<Button x:Name="btnIncrease" Margin="4,0">Increase</Button>
<Button x:Name="btnDecrease" Margin="4,0">Decrease</Button>
</UniformGrid>
</Grid>
</Window>
Main Window Constructor (only code in code-behind)
public Window1()
{
InitializeComponent();
btnIncrease.Click += (s, e) =>
{
lstInfo.Items.Add(String.Format("{0} Increase Button Pressed", DateTime.Now.ToString("HH:mm:ss.ffff")));
textBlock2.Height += 30;
};
btnDecrease.Click += (s, e) =>
{
lstInfo.Items.Add(String.Format("{0} Decrease Button Pressed", DateTime.Now.ToString("HH:mm:ss.ffff")));
if (textBlock2.ActualHeight >= 30)
textBlock2.Height -= 30;
};
grid1.ReportInfo += (s, e) => lstInfo.Items.Add(String.Format("{0} Left Grid: {1}", e.TimeStamp.ToString("HH:mm:ss.ffff"), e.Message));
grid2.ReportInfo += (s, e) => lstInfo.Items.Add(String.Format("{0} Right Grid: {1}", e.TimeStamp.ToString("HH:mm:ss.ffff"), e.Message));
}