Gallery like WP system gallery with pinchtozoom - gallery

I'm trying to reproduce a gallery like the system gallery, but i have a problem with pinch to zoom, the container doesn't enlarge and the picturs overlays, I tried to use with listbox:
<ListBox x:Name="pictureListBox" Margin="10,10,10,0" ItemsSource="{Binding}" ScrollViewer.HorizontalScrollBarVisibility="Visible" VerticalAlignment="Top">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="3">
<StackPanel>
<Image x:Name="Image" Source="{Binding Source}" Width="400" Stretch="Uniform" Canvas.ZIndex="1">
<Image.RenderTransform>
<CompositeTransform x:Name="transform" />
</Image.RenderTransform>
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener PinchStarted="OnPinchStarted" PinchDelta="OnPinchDelta" DragDelta="OnDragDelta" />
</toolkit:GestureService.GestureListener>
</Image>
</StackPanel>
<!--<Image Source="/Images/gallery_loading.jpg" Width="150" Height="150" Stretch="Uniform"/>-->
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and with panorama:
<phone:Panorama x:Name="panorama" Margin="0,0,0,0" ItemsSource="{Binding}" Width="550">
<phone:Panorama.HeaderTemplate>
<DataTemplate>
<TextBlock Text=""/>
</DataTemplate>
</phone:Panorama.HeaderTemplate>
<phone:Panorama.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Source}" Margin="5">
<Image.RenderTransform>
<CompositeTransform x:Name="transform" />
</Image.RenderTransform>
<toolkit:GestureService.GestureListener>
<toolkit:GestureListener PinchStarted="OnPinchStarted" PinchDelta="OnPinchDelta" DragDelta="OnDragDelta" />
</toolkit:GestureService.GestureListener>
</Image>
</DataTemplate>
</phone:Panorama.ItemTemplate>
</phone:Panorama>
here is the c# code:
Image image = null;
CompositeTransform transform = null;
private void OnPinchStarted(object sender, PinchStartedGestureEventArgs e)
{
image = sender as Image;
transform = image.RenderTransform as CompositeTransform;
//initialAngle = transform.Rotation;
initialScale = transform.ScaleX;
}
private void OnPinchDelta(object sender, PinchGestureEventArgs e)
{
//transform.Rotation = initialAngle + e.TotalAngleDelta;
transform.ScaleX = initialScale * e.DistanceRatio;
transform.ScaleY = initialScale * e.DistanceRatio;
}
Thanks all

Related

Xamarin CollectionView - Scroll Programatically

I have collection view . See below code
<CollectionView ItemsSource="{Binding photos}" HeightRequest="300"
ItemSizingStrategy="MeasureAllItems" Margin="10,0,10,0"
x:Name="photosView"
ItemsUpdatingScrollMode="KeepScrollOffset">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="3" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Padding="2">
<Frame BackgroundColor="Red" HeightRequest="79" WidthRequest="53" Padding="0" Margin="0"
IsClippedToBounds="True" HasShadow="False" CornerRadius="10">
<Image Aspect="AspectFill" Source="{Binding imageUrl}"/>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
I am showing 3 rows and 3 columns of the images. If I have more than 9 images then I am showing Button which says Scroll for more photos. Now On click on the imageI have below code
void OnScrollMore(System.Object sender, System.EventArgs e)
{
//photosView.SendScrolled(new ItemsViewScrolledEventArgs() { FirstVisibleItemIndex = 0 });
photosView.ScrollTo(photosView.Y + 10, position: ScrollToPosition.MakeVisible, animate: true);
}
But nothing is happening . It is not getting scrolled to next row.
Any suggestions?
The reason your ScrollTo method is not working is because the photosView can't find the item 'photosView.Y + 10' in your photosView itemssource. The method you're invoking is trying to find an item in the ItemsSource. It is not scrolling to a y-position like you're trying to do. You can see it in the description of the method when going to the definition. It is waiting for an 'object item'.
public void ScrollTo(object item, object group = null, ScrollToPosition position = ScrollToPosition.MakeVisible, bool animate = true);
If what you're trying to do is scroll to the last added item of the collectionview, then try this working approach and build it up from there. Here everytime you press the button, an item (string) gets added. This item is set as the ScrollTo object at the end of the button click handler.
MainPage.xaml
<StackLayout Orientation="Vertical">
<CollectionView ItemsSource="{Binding photos}" HeightRequest="300"
ItemSizingStrategy="MeasureAllItems" Margin="10,0,10,0"
x:Name="photosView"
ItemsUpdatingScrollMode="KeepLastItemInView">
<CollectionView.ItemsLayout>
<GridItemsLayout Orientation="Vertical" Span="3" />
</CollectionView.ItemsLayout>
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Padding="2">
<Frame BackgroundColor="Red" HeightRequest="79" WidthRequest="53" Padding="0" Margin="0"
IsClippedToBounds="True" HasShadow="False" CornerRadius="10">
<Label Text="{Binding}" TextColor="White"
HorizontalOptions="Center" VerticalOptions="Center"
HorizontalTextAlignment="Center" VerticalTextAlignment="Center"/>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Button Text="scroll more" HorizontalOptions="Center" VerticalOptions="End" Clicked="OnScrollMore"/>
</StackLayout>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
ObservableCollection<string> ObservableItems { get; set; }
public MainPage()
{
InitializeComponent();
ObservableItems = new ObservableCollection<string>(new List<string>() { "een", "twee", "drie" });
photosView.ItemsSource = ObservableItems;
}
void OnScrollMore(System.Object sender, System.EventArgs e)
{
var item = (ObservableItems.Count + 1).ToString();
ObservableItems.Add(item);
photosView.ScrollTo(item, position: ScrollToPosition.MakeVisible, animate: true);
}
}
Resulting in:

On using Detect Shake functionality in xamarin.forms UI is calling multiple times

I am working with xamarin.forms shake delect functionality, where on shaking the mobile I am calling a popup screen, but that screen is calling multiple times till I wont stop shaking the phone
RateUsPage.xaml
<?xml version="1.0" encoding="UTF-8"?>
<pages:PopupPage Title="Rate Us"
BackgroundColor="{DynamicResource TransparentPurple}"
Padding="0">
<pages:PopupPage.Animation>
<animations:ScaleAnimation PositionIn="Center" PositionOut="Center" ScaleIn="1.2" ScaleOut="0.8" DurationIn="400" DurationOut="300" EasingIn="SinOut" EasingOut="SinIn" HasBackgroundAnimation="True" />
</pages:PopupPage.Animation>
<StackLayout VerticalOptions="Center" HorizontalOptions="Center" Margin="20">
<StackLayout>
<Label Text="Rate Your Experience !!!" FontSize="{DynamicResource FontSize14}"/>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding Star1}" Grid.Row="0" Grid.Column="0">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding StarTappedCommand}" CommandParameter="1"/>
</Image.GestureRecognizers>
</Image>
<Image Source="{Binding Star2}" Grid.Row="0" Grid.Column="1">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding StarTappedCommand}" CommandParameter="2"/>
</Image.GestureRecognizers>
</Image>
<Image Source="{Binding Star3}" Grid.Row="0" Grid.Column="2">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding StarTappedCommand}" CommandParameter="3"/>
</Image.GestureRecognizers>
</Image>
<Image Source="{Binding Star4}" Grid.Row="0" Grid.Column="3">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding StarTappedCommand}" CommandParameter="4"/>
</Image.GestureRecognizers>
</Image>
<Image Source="{Binding Star5}" Grid.Row="0" Grid.Column="4">
<Image.GestureRecognizers>
<TapGestureRecognizer Command="{Binding StarTappedCommand}" CommandParameter="5"/>
</Image.GestureRecognizers>
</Image>
</Grid>
</StackLayout>
<StackLayout>
<Grid Padding="10" RowSpacing="0" ColumnSpacing="15" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<Button Padding="0" Grid.Row="0" Grid.Column="0" Command="{Binding CloseCommand}" FontSize="{DynamicResource FontSize14}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Text="{Binding CancelText}"/>
</Grid>
</StackLayout>
</StackLayout>
</pages:PopupPage>
RateUsPageViewModel.cs
public class RateUsPageViewModel{
public RateUsPageViewModel(){
try
{
if (Accelerometer.IsMonitoring)
Accelerometer.Stop();
else
Accelerometer.Start(SensorSpeed.Game);
}
catch (FeatureNotSupportedException fnsEx)
{
// Feature not supported on device
}
catch (Exception ex)
{
// Other error has occurred.
}
Accelerometer.ShakeDetected += Accelerometer_ShakeDetected;
}
private void Accelerometer_ShakeDetected(object sender, EventArgs e)
{
MainThread.BeginInvokeOnMainThread(() =>
{
_navigationService.ShowPopup<RatingUsPageViewModel>();
});
}
}
so when I use this code my UI is calling number of times
please help
thanks in advance
Remove your try and catch blocks and implement ToggleAccelerometer() method. call ToggleAccelerometer() method in your constructor and then again call in Accelerometer_ShakeDetected(object sender, EventArgs e). It should stop your problem.
public class RateUsPageViewModel
{
public RateUsPageViewModel()
{
ToggleAccelerometer();
Accelerometer.ShakeDetected += Accelerometer_ShakeDetected;
}
private void Accelerometer_ShakeDetected(object sender, EventArgs e)
{
MainThread.BeginInvokeOnMainThread(() =>
{
ToggleAccelerometer();
_navigationService.ShowPopup<RatingUsPageViewModel>();
});
}
public void ToggleAccelerometer()
{
try
{
if (Accelerometer.IsMonitoring)
Accelerometer.Stop();
else
Accelerometer.Start(speed);
}
catch (FeatureNotSupportedException fnsEx)
{
// Feature not supported on device
}
catch (Exception ex)
{
// Other error has occurred.
}
}
}

How to get the itemlistview details when a button is clicked

When a Add to cart button is clicked i want clicked row to add to local database.
i tried to implement clicked option, but is shows System.InvalidCastException: Specified cast is not valid.
My Xaml is :
<controls:FlowListView x:Name="gallery"
FlowColumnCount="2"
SeparatorVisibility="Default"
HasUnevenRows="True"
FlowItemsSource="{Binding ItemsGallery}"
FlowUseAbsoluteLayoutInternally="True"
FlowItemTapped="OnFlowItemTapped"
FlowColumnExpand="Proportional"
BackgroundColor="White">
<controls:FlowListView.FlowColumnTemplate>
<DataTemplate>
<StackLayout>
<Frame BorderColor="#DCDCDC" HasShadow="True" Margin="2,2,2,2" CornerRadius="5">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="35"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="35"/>
</Grid.RowDefinitions>
<ffimageloading:CachedImage Source="{Binding image}" Grid.Row="0" LoadingPlaceholder="ItemsGallery" HeightRequest="120" WidthRequest="120" />
<Label Grid.Row="1"
VerticalOptions="End"
FontAttributes="Bold"
FontSize="Medium"
HorizontalTextAlignment="Start"
TextColor="Black"
Text="{Binding name}" />
<Label Grid.Row="2" HorizontalOptions="Start"
VerticalOptions="End"
FontAttributes="Bold"
FontSize="Medium"
Text="{Binding weight}" />
<Label HorizontalOptions="Start" Grid.Row="3"
VerticalOptions="End"
FontAttributes="Bold"
FontSize="Medium"
Margin="2"
Text="{Binding price}" />
<Button Text="Add TO Cart" Grid.Row="4" BackgroundColor="Coral" TextColor="WhiteSmoke" Clicked="Button_Clicked_1" />
</Grid>
</Frame>
</StackLayout>
</DataTemplate>
</controls:FlowListView.FlowColumnTemplate>
</controls:FlowListView>
and my logic is :
private async void Button_Clicked_1(object sender, EventArgs e)
{
if (((ListView)sender).SelectedItem == null)
return;
var myList = (ListView)sender;
var myProuct= (myList.SelectedItem as ProductDetail);
}
the sender of a Button Click event will be a BUTTON, not the ListView containing the button
private async void Button_Clicked_1(object sender, EventArgs e) {
// the sender of a button click event is a BUTTON
var btn = (Button)sender;
var myProduct = (ProductDetail)btn.BindingContext;
}
You could go with regular data binding way with viewmodel, or you can try this
Button Text="Add TO Cart" Grid.Row="4" BackgroundColor="Coral" TextColor="WhiteSmoke" Command="{Binding AddCommand}" CommandParameter = "{Binding .}"
But then you would need to edit the model building up ItemsGallery list.
public ICommand AddCommand { get; set; }
And when you are creating your objects
new Gallery
{
//your stuff
AddCommand = new Command<Gallery>(async (item) => await
AddItem(item))
})
private async Task AddItem(Gallery item)
{
//your implementation
}

How to binding the DataContext of an user-control?

I have a user-control like this:
<UserControl x:Class="IPAddressWPFUserControl.IPAddressControl"
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"
mc:Ignorable="d" BorderThickness="0" OverridesDefaultStyle="False" BorderBrush="{x:Null}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" x:Name="txtboxFirstPart" TextChanged="txtbox_TextChanged" MaxLength="3" BorderThickness="0" TabIndex="1" PreviewKeyDown="txtboxFirstPart_PreviewKeyDown" PreviewKeyUp="txtboxFirstPart_PreviewKeyUp" Width="31" />
<Label Content="." Grid.Column="1" x:Name="label1" VerticalContentAlignment="Bottom" HorizontalAlignment="Left" Background="White" />
<TextBox Grid.Column="2" x:Name="txtboxSecondPart" MaxLength="3" TextChanged="txtbox_TextChanged" BorderThickness="0" TabIndex="2" KeyDown="txtboxSecondPart_KeyDown" PreviewKeyUp="txtboxSecondPart_PreviewKeyUp" Margin="0" HorizontalAlignment="Left" Width="31"/>
<Label Content="." Grid.Column="3" Grid.Row="0" x:Name="label2" VerticalContentAlignment="Bottom" HorizontalAlignment="Left" Background="White" />
<TextBox Grid.Column="4" x:Name="txtboxThridPart" MaxLength="3" TextChanged="txtbox_TextChanged" BorderThickness="0" TabIndex="3" VerticalContentAlignment="Bottom" KeyDown="txtboxThridPart_KeyDown" PreviewKeyUp="txtboxThridPart_PreviewKeyUp" Width="31" HorizontalContentAlignment="Center" />
<Label Content="." Grid.Column="5" x:Name="label3" VerticalContentAlignment="Bottom" HorizontalAlignment="Left" Background="White" />
<TextBox Grid.Column="6" x:Name="txtboxFourthPart" MaxLength="3" TextChanged="txtbox_TextChanged" BorderThickness="0" TabIndex="4" VerticalContentAlignment="Bottom" HorizontalAlignment="Left" Width="31" HorizontalContentAlignment="Center" />
</Grid>
Added Text property to it in the code behind:
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(IPAddressControl),
new PropertyMetadata("0.0.0.0", new PropertyChangedCallback(OnTextPropertyChanged)));
private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
IPAddressControl o = d as IPAddressControl;
try
{
var value = e.NewValue as string;
var splitValues = new string[4];
if (value != null)
{
var splits = value.Split(new char[] { '.' }, StringSplitOptions.None);
Array.Copy(splits, splitValues, splits.Length);
}
o.txtboxFirstPart.Text = splitValues[0];
o.txtboxSecondPart.Text = splitValues[1];
o.txtboxThridPart.Text = splitValues[2];
o.txtboxFourthPart.Text = splitValues[3];
}
catch (Exception ex)
{
throw new Exception("Error in IP control see inner exception!", ex);
}
o.RaiseTextChanged(e);
}
public string Text
{
get { return (string)this.GetValue(IPAddressControl.TextProperty); }
set { this.SetValue(IPAddressControl.TextProperty, value); }
}
public event DependencyPropertyChangedEventHandler TextChanged;
protected virtual void RaiseTextChanged(DependencyPropertyChangedEventArgs e)
{
if (this.TextChanged != null)
{
this.TextChanged(this, e);
}
}
When I am using it in the MainWindow like this:
<GroupBox Name="gb_Tcp" DataContext="{Binding TcpCollection}">
<my:IPAddressControl x:Name="tb_IpAddress" Text="{Binding Path=IpAddress, ElementName=gb_tcp}"/>
<TextBox x:Name="tb_Test" Text={Binding Path=IpAddress, ElementName=gb_tcp}" />
</GroupBox>
The problem is when I try to set the value in a button click event:
private void btn_IpReset_Click(object sender, RoutedEventArgs e)
{
tb_IpAddress.Text = source.IpAddress; //This failed to change
tb_Test.Text= source.IpAddress; //This changed successfully
}
I suppose this is because the user-control didn't change the datacontext to the MainWindow's? Or what could be the problem is? Thanks in advance!
It's because you didn't use a BindingMode that will update source like TwoWay or OneWayToSource. So, after tb_IpAddress.Text = source.IpAddress, the binding you have set will be overwrite by the local value. tb_Test.Text= source.IpAddress work because TextBox.Text's default binding mode is TwoWay.

how rebind silverlight datagrid

I am just doing simple example in Silverlight, which retrieves data from database, can also insert, update and delete
I use child window for insert command, when I click "OK" Button at this ChildWindow it insert's in database but not renders on page(Silverlight content), there is same records therefore in database really inserts information. only after again re-lunch this page, it shows correctly(retrieves all data from server)
I'll post my source
this is Customers.xaml file
<UserControl x:Class="Store.Customers"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mv="clr-namespace:Store.ViewModel"
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="1000">
<UserControl.Resources>
<mv:ViewModel x:Key="ViewModel"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="127*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="130*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="91*" />
<RowDefinition Height="99*" />
<RowDefinition Height="110*" />
</Grid.RowDefinitions>
<Button Name="btnEdit" Content="Edit" HorizontalAlignment="Right" Grid.Column="1" Width="55" Height="30" Margin="0,225,0,0" Click="btnEdit_Click" />
<data:DataGrid Name="dgCustomer"
AutoGenerateColumns="False" VerticalScrollBarVisibility="Visible"
ItemsSource="{Binding PagedView, Mode=TwoWay, Source={StaticResource ViewModel}}"
Grid.Row="1" Grid.Column="1">
<data:DataGrid.Columns>
<data:DataGridTextColumn Header="ID" Binding="{Binding CustomerID}"/>
<data:DataGridTextColumn Header="CompanyName" Binding="{Binding CompanyName}"/>
<data:DataGridTextColumn Header="ContactName" Binding="{Binding ContactName}"/>
<data:DataGridTextColumn Header="ContactTitle" Binding="{Binding ContactTitle}"/>
<data:DataGridTextColumn Header="Address" Binding="{Binding Address}"/>
<data:DataGridTextColumn Header="City" Binding="{Binding City}"/>
<data:DataGridTextColumn Header="Region" Binding="{Binding Region}"/>
<data:DataGridTextColumn Header="PostalCode" Binding="{Binding PostalCode}"/>
<data:DataGridTextColumn Header="Country" Binding="{Binding Country}"/>
<data:DataGridTextColumn Header="Phone" Binding="{Binding Phone}"/>
<data:DataGridTextColumn Header="Fax" Binding="{Binding Fax}"/>
<data:DataGridCheckBoxColumn Header="IsCitizen" Binding="{Binding IsCitizen}"/>
</data:DataGrid.Columns>
</data:DataGrid>
<data:DataPager HorizontalContentAlignment="Center" x:Name="myPager"
Source="{Binding ItemsSource, ElementName=dgCustomer}"
AutoEllipsis="True"
PageSize="10" Grid.Row="2" Grid.Column="1" VerticalAlignment="Top"/>
</Grid>
and this codebehinde
public partial class Customers : UserControl
{
public Customers()
{
InitializeComponent();
}
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
new AddNewCustomer().Show();
}
}
this is childwindow
<controls:ChildWindow x:Class="Store.AddNewCustomer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
xmlns:mv="clr-namespace:Store.ViewModel"
Width="450" Height="350"
Title="AddNewCustomer" >
<controls:ChildWindow.Resources>
<mv:ViewModel x:Key="ViewModel"/>
</controls:ChildWindow.Resources>
<Grid x:Name="LayoutRoot" Margin="2">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid>
<Grid.RowDefinitions >
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="30*"></ColumnDefinition>
<ColumnDefinition Width="70*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="0" Text="Customer ID :" VerticalAlignment="Center" Margin="2,0,0,0" />
<TextBox Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" Margin="2,0" x:Name="txtCustomerID"
Text="{Binding CustomerID, Mode=TwoWay, Source={StaticResource ViewModel}}" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="Company Name :" VerticalAlignment="Center" Margin="2,0,0,0" />
<TextBox Grid.Row="2" Grid.Column="1" VerticalAlignment="Center" Margin="2,0" x:Name="txtCompanyName"
Text="{Binding CompanyName, Mode=TwoWay, Source={StaticResource ViewModel}}"/>
<TextBlock Grid.Row="3" Grid.Column="0" Text="Contact Name :" VerticalAlignment="Center" Margin="2,0,0,0" />
<TextBox Grid.Row="3" Grid.Column="1" VerticalAlignment="Center" Margin="2,0" x:Name="txtContactName" />
<TextBlock Grid.Row="4" Grid.Column="0" Text="Contact Title :" VerticalAlignment="Center" Margin="2,0,0,0" />
<TextBox Grid.Row="4" Grid.Column="1" VerticalAlignment="Center" Margin="2,0" x:Name="txtContactTitle" />
<TextBlock Grid.Row="5" Grid.Column="0" Text="Address :" VerticalAlignment="Center" Margin="2,0,0,0" />
<TextBox Grid.Row="5" Grid.Column="1" VerticalAlignment="Center" Margin="2,0" x:Name="txtAddressTitle" />
<TextBlock Grid.Row="6" Grid.Column="0" Text="City :" VerticalAlignment="Center" Margin="2,0,0,0" />
<TextBox Grid.Row="6" Grid.Column="1" VerticalAlignment="Center" Margin="2,0" x:Name="txtCity" />
<TextBlock Grid.Row="7" Grid.Column="0" Text="Country :" VerticalAlignment="Center" Margin="2,0,0,0" />
<TextBox Grid.Row="7" Grid.Column="1" VerticalAlignment="Center" Margin="2,0" x:Name="txtCountry" />
</Grid>
<Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />
<Button x:Name="OKButton" Content="OK" Width="75" Height="23" HorizontalAlignment="Right" Click="OKButton_Click"
Margin="0,12,79,0" Grid.Row="1" Command="{ Binding AddNewCustomer, Mode=TwoWay, Source={StaticResource ViewModel} }"/>
</Grid>
this is My ViewModel
public class ViewModel : BaseViewModel
{
#region Fields
public ObservableCollection<Customer> _items;
public PagedCollectionView _view;
public string _customerID;
public string _companyName;
#endregion
#region Constructors
public ViewModel()
{
if (!this.IsDesignTime)
this.LoadCustomer();
}
#endregion
#region Properties
public ICommand AddNewCustomer { get { return new AddNewCustomerInfo(this); } }
public ObservableCollection<Customer> Items
{
get { return this._items; }
set
{
this._items = value;
this.OnPropertyChanged("Items");
}
}
public PagedCollectionView PagedView
{
get { return this._view; }
set
{
this._view = value;
this.OnPropertyChanged("PagedView");
}
}
public string CustomerID
{
get { return this._customerID;}
set
{
this._customerID = value;
this.OnPropertyChanged("CustomerID");
}
}
public string CompanyName
{
get { return this._companyName; }
set
{
this._companyName = value;
this.OnPropertyChanged("CompanyName");
}
}
#endregion
#region Methods
public void LoadCustomer()
{
DataServiceClient webService = new DataServiceClient();
webService.GetCustomersCompleted += new EventHandler<GetCustomersCompletedEventArgs>(webService_GetCustomersCompleted);
webService.GetCustomersAsync();
}
public void webService_GetCustomersCompleted(object sender, GetCustomersCompletedEventArgs e)
{
Items = e.Result;
PagedCollectionView pageView = new PagedCollectionView(Items);
pageView.PageSize = 10;
PagedView = pageView;
}
public void CreateCustomer()
{
DataServiceClient webservice = new DataServiceClient();
Customer cust = new Customer();
cust.CustomerID = this.CustomerID;
cust.CompanyName = this.CompanyName;
webservice.InsertCustomerCompleted += new EventHandler<InsertCustomerCompletedEventArgs>(webservice_InsertCustomerCompleted);
webservice.InsertCustomerAsync(cust);
LoadCustomer();
}
void webservice_InsertCustomerCompleted(object sender, InsertCustomerCompletedEventArgs e)
{
this.CreateResult = e.Result;
}
#endregion
}
public class AddNewCustomerInfo : ICommand
{
#region Fields
public ViewModel ViewModel { get; set; }
#endregion
#region Constructors
public AddNewCustomerInfo(ViewModel viewModel)
{
this.ViewModel = viewModel;
}
#endregion
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
this.ViewModel.CreateCustomer();
}
}
Grid and childwindow looks like this
As a simple basic solution, i would do this:
change your InsertCustomer web service call to return the updated Customer object that it just saved. This is so you will get an updated copy of the data object, complete with any keys/IDs. Doing this is a reasonably efficient way to do it, as you are making a call and accessing the database anyway, there is no point making two calls when it can be done in one.
once you've changed your webservice contract and regenerated your client proxy, the InsertCustomerCompletedEventArgs Result property should contain the updated Customer object. If you now add this data object to your PagedCollectionView it will automatically show up in your grid (as the PagedCollectionView implements INotifyCollectionChanged so the DataGrid binding will pick it up straight away, although be aware that paging may mean it isn't visible in the list you are currently looking at).

Resources