Binding datatable to xamdatagrid - binding

I don't know how to add columns to xamDatagrid and Binding a datatalbe to this.
Anyone can help me?
DataTable dt = new DataTable();
dt.Columns.Add("Kieu", typeof(int));
dt.Columns[0].DefaultValue = 1;
dt.Columns.Add("Ngay", typeof(DateTime));
dt.Columns[1].DefaultValue = DateTime.Today;
dt.Rows.Add();

You can do this:
XAML:
<Window x:Class="WPFXamDataGrid.MainWindow"
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-mpatibility/2006"
xmlns:igDP="http://infragistics.com/DataPresenter"
xmlns:local="clr-namespace:WPFXamDataGrid"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<igDP:XamDataGrid x:Name="xamDataGrid" Loaded="XamDataGrid_Loaded">
<igDP:XamDataGrid.FieldLayouts>
<igDP:FieldLayout>
<igDP:Field Name="Kieu"/>
<igDP:Field Name="Ngay"/>
</igDP:FieldLayout>
</igDP:XamDataGrid.FieldLayouts>
</igDP:XamDataGrid>
</Grid>
</Window>
Code Behind:
using System;
using System.Windows;
using System.Data;
namespace WPFXamDataGrid
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void XamDataGrid_Loaded(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Kieu", typeof(int));
dt.Columns.Add("Ngay", typeof(DateTime));
dt.Rows.Add(1, DateTime.Now);
xamDataGrid.DataSource = dt.DefaultView;
}
}
}

Related

Xamarin forms Binded Webview shows on Android but not on IOS from an awaited task

I have created a new Xamarin Forms Prism project to duplicate this issue I am having with my actual app. I want to go to my data/web service and fetch announcements for the front page of my app. It is just an HTML string so I am using a WebView and my MainPage.xaml looks like .
<?xml version="1.0" encoding="utf-8" ?>
<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Button Text="Go to page 1" Command="{Binding NextPageCommand}"/>
<WebView x:Name="webView" WidthRequest="1000" HeightRequest="1000" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<WebView.Source>
<HtmlWebViewSource Html="{Binding Announcements}"/>
</WebView.Source>
</WebView>
</StackLayout>
And my ViewModel
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlankApp1.ViewModels
{
public class MainPageViewModel : ViewModelBase,INavigatedAware
{
public MainPageViewModel(INavigationService navigationService)
: base (navigationService)
{
Title = "Main Page";
NextPageCommand = new DelegateCommand(NextPage);
}
public DelegateCommand NextPageCommand { get; }
private string _announcements;
public string Announcements
{
get { return _announcements; }
set { SetProperty(ref _announcements, value); }
}
private async void NextPage()
{
await NavigationService.NavigateAsync("Page1");
}
public async void OnNavigatedTo(NavigationParameters parameters)
{
if (Announcements == null)
{
Announcements = "<html><body>" + "Working Shows this HTML in the Webview" + "</body></html>";
}
else
{
Announcements = "<html><body>" + "Not Working, Didnt update with this new HTML" + "</body></html>";
}
}
public async void OnNavigatedFrom(NavigationParameters parameters)
{
//throw new NotImplementedException();
}
}
}
In the OnNavgatedTo function it does not update the HTML that is displayed when you Navigate away from this page and then return.
If anyone out there knows why this might be working fine on android but not iOS please let me know. I have been looking at this for 2 days now and still can not get it to display like it does on Android
If you want to change the WebView's content, try to bind its HtmlWebViewSource instead of Html.
Create your HtmlWebViewSource property in your viewmodel:
private HtmlWebViewSource _webviewSource;
public HtmlWebViewSource WebviewSource
{
get { return _webviewSource; }
set
{
SetProperty(ref _webviewSource, value);
}
}
Then bind it like:
<WebView x:Name="webView" WidthRequest="1000" HeightRequest="1000" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Source="{Binding WebviewSource}">
When you want to change it, try this:
if (WebviewSource == null)
{
WebviewSource = new HtmlWebViewSource { Html = "<html><body>" + "Working Shows this HTML in the Webview" + "</body></html>" };
}
else
{
WebviewSource = new HtmlWebViewSource { Html = "<html><body>" + "Not Working, Didnt update with this new HTML" + "</body></html>" };
}
Honestly I don't really understand what you're trying to do with the Task.Run.
Just do:
public async void OnNavigatedTo(NavigationParameters parameters)
{
try
{
//GetAnnouncements
Announcements = "<html><body>" + await App.dataService.GetAnnouncements() + "</body></html>";
}
catch (System.OperationCanceledException ex)
{
Console.WriteLine($"announcement load cancelled: {ex.Message}");
}
Also I think newest versions of Prism have Task based navigation methods.
Update:
You updated your question.
I suspect your problem is that you don't navigate to your MainPage but do MainPage = new MainPage(). Hence OnNavigatedTo is never called and Announcement is never set.

Binding between Data template and ListBox - Windows Phone

I'm having problems to do a binding in Windows Phone. Hope you can help me.
I have the following Data Template:
<DataTemplate>
<TextBox Name="txt1"/>
<TextBox Name="txt2"/>
</DataTemplate>
I have a ListBox that receives the following Class in the ItemsSource Property:
public class Product
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
Is there anyway to bind the Text property with the Object of the ListBoxItem like...
<TextBox Name="txt1" Text={Binding ElementName=ListBox, Path=SelectedItem.Product.Name}/>
I got a working example
xaml:
Here's the code
<Grid x:Name="gdTest" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="5,0,5,0" >
<ListBox Width="400" Margin="10" x:Name="lstDemo">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Id}" Margin="20" />
<TextBlock Text="{Binding Path=Name}" Margin="20"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StackOverFlowTestApp.Resources;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.UserData;
using Windows.UI;
using System.Windows.Media;
using System.IO;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;
namespace StackOverFlowTestApp
{
public partial class MainPage : PhoneApplicationPage
{
private SoundEffect effect;
// Constructor
public MainPage()
{
InitializeComponent();
List<Product> liProd = new List<Product>();
for (int i = 0; i < 10; i++) {
liProd.Add(new Product()
{
Id = i,
Name = "Anobik" + i.ToString()
});
}
lstDemo.ItemsSource = liProd;
}
}
public class Product
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
}
}
if you require any more explanation then let me know.

UserControl Dependencyproperty not updating through binding

I'm creating a Windows 8 app, and I'm struggling the last couple of days with a custom user control. I can't really figure out whats wrong.
The weird thing is that the dependencyproperty calls the propertychanged event when I change Source in code, but with the binding its not updating.
So here's my code:
GamePage.xaml.cs
public sealed partial class GamePage
{
GamePageViewModel viewModel;
public GamePage()
{
this.InitializeComponent();
viewModel = new GamePageViewModel();
}
}
GamePage.xaml
<common:LayoutAwarePage x:Class="WordSearcher.GamePage"
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:common="using:WordSearcher.Common"
xmlns:controls="using:WordSearcher.Controls"
xmlns:ignore="http://www.ignore.com"
mc:Ignorable="d ignore"
d:DesignHeight="768"
d:DesignWidth="1366"
DataContext="{Binding GamePageViewModel, Source={StaticResource Locator}}">
<StackPanel Orientation="Horizontal">
<StackPanel.Background>
<ImageBrush ImageSource="Assets/Wood.jpg" Stretch="UniformToFill"/>
</StackPanel.Background>
<controls:PuzzleControl Source="{Binding Path=PuzzleData}"/>
</StackPanel>
</common:LayoutAwarePage>
GamePageViewModel.cs
public class GamePageViewModel : ViewModelBase
{
private List<string> _puzzleData;
public List<string> PuzzleData
{
get
{
return _puzzleData;
}
set
{
this._puzzleData = value;
RaisePropertyChanged("PuzzleData");
}
}
public GamePageViewModel()
{
SetNewData();
}
private async void SetNewData()
{
await SomeManager.Prepare();
PuzzleData = SomeManager.Create(20);
}
}
PuzzleControl.xaml.cs
<UserControl
x:Class="WordSearcher.Controls.PuzzleControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WordSearcher.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="500"
d:DesignWidth="500">
<Grid x:Name="puzzleGrid"
Width="500"
Height="500"
>
</Grid>
</UserControl>
PuzzleControl.xaml.cs
public sealed partial class PuzzleControl : UserControl
{
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(ObservableCollection<string>), typeof(PuzzleControl), new PropertyMetadata(null, PropertyChanged));
private static void PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//
// not called from binding
//
((PuzzleControl)d).OnItemsSourcePropertyChanged(e);
}
private void OnItemsSourcePropertyChanged(DependencyPropertyChangedEventArgs e)
{
Source = (ObservableCollection<string>)e.NewValue;
SetGridData();
}
public ObservableCollection<string> Source
{
get
{
return (ObservableCollection<string>)GetValue(SourceProperty);
}
set
{
SetValue(SourceProperty, value);
}
}
public PuzzleControl()
{
this.InitializeComponent();
CreateRowsAndColumns();
}
private void CreateRowsAndColumns()
{
//create rows and columns in puzzleGrid
//works fine
}
private void SetGridData()
{
//fill puzzleGrid with data
//works fine
}
}
Does anyone knows with is wrong in my code? Because when I put Source = new ObservableCollection(); in the constructor of PuzzleData, the PropertyChanged event will raise. Is it anything with the DataContext?
Thnx in advance!
I don't know for sure,
but you set <controls:PuzzleControl Source="{Binding Path=PuzzleData}"/>
PuzzleData = List<string>
and
Source = ObservableCollection<string>
If the binding even works the first time (what it apperantly does) then it might be the case the source is set to List<string> in some way instead of ObservableCollection<string>. That might be the case why your dependencyproperty method (PropertyChanged) is not called because it is registered to ObservableCollection<string>.
But this is all pure speculation, haven't tested it.
After I got his code an reviewed it I found out that the PuzzleData was never really set and that that was the error... False Alarm....
Are you sure binding context? And How binding object? If you use your user control like in a gridview, DataContext is changed, and differend Datacontext of root page.
<controls:PuzzleControl Source="{Binding Path=DataContext.PuzzleData}"/>
if you use sub control, your user control; bind ElementName property like this:
<controls:PuzzleControl Source="{Binding Path=DataContext.PuzzleData, ElementName=pageRoot}"/>
If you not sure, tracing DataContext binding values on debug via breakpoints.

how to define events in mvvm model in Silverlight

i have an combox control defined with events in my mainpage.xaml
<Grid x:Name="LayoutRoot">
<ComboBox SelectionChanged="ComboBox_SelectionChanged"></ComboBox>
</Grid>
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
now how do we defined events for combox control in mvvm model .
and how do we bind the collection list to combo box. i am using SL 3
thanks
prince
In your xaml, you can bind the ItemSource and SelectedItem as shown below:
MainPage.xaml
<UserControl x:Class="App1.MainPage"
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:local="clr-namespace:App1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.DataContext>
<local:MainPage_ViewModel/>
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="White">
<ComboBox ItemsSource="{Binding MyItems}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" SelectionChanged="ComboBox_SelectionChanged" Height="30" Width="100"/>
</Grid>
In the MainPage.xaml.cs, your Selection changed method could just call the method on your ViewModel since you are using SL3:
MainPage.xaml.cs
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private MainPage_ViewModel viewModel
{
get { return this.DataContext as MainPage_ViewModel; }
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.viewModel.SelectionChanged();
}
}
Your ViewModel would have the MyItems collection and the SelectedItem to bind to:
MainPage_ViewModel.cs
public class MainPage_ViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> MyItems
{
get { return myItems; }
set { myItems = value; }
}
private ObservableCollection<string> myItems = new ObservableCollection<string>() { "One", "Two", "Three" };
public string SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; }
}
private string selectedItem = string.Empty;
public void SelectionChanged()
{
//Perform logic that needs to happen when selection changes
}
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Depending on what you were using your SelectionChanged method for, you may no longer need it since this would bind the SelectedItem to the ViewModel.
Hope this helps!

Problem Binding via command.Can you help

New to wpf and through a learning curve.
I have a userControl with a Toolbar Save Button and a TextBox.
What I am trying to achieve is as follows
When I press the save Button in the toolbar I should record in the textbox that I am about to save and that I have saved the customer (CustomerView UserControl)
I seem to have 2 problems
1) that the SaveCommand is not hooked I thought I had hooked it
2) is not writing the action to the textbox.
Could you tell me where I am going wrong?
Thanks a lot!!!
MainWindow.xaml
<Window x:Class="MyCompany.CustomerStore.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:view="clr-namespace:MyCompany.CustomerStore.Views"
Title="MainWindow" Height="350" Width="525">
<Grid>
<view:CustomerView></view:CustomerView>
</Grid>
CustomerView.xaml
<UserControl x:Class="MyCompany.CustomerStore.Views.CustomerView"
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"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<DockPanel LastChildFill="True">
<ToolBar DockPanel.Dock="Top">
<Button Command="{Binding Path=SaveCommand}">Save</Button>
</ToolBar>
<TextBox Name="txtPrintAction" Text="{Binding CustomerLog, Mode=TwoWay}"></TextBox>
</DockPanel>
</Grid>
CustomerModel.cs
public class CustomerModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string CustomerLog { get; set; }
}
CustomerViewModel.cs
public class CustomerViewModel:WorkspaceViewModel,ICustomerViewModel
{
readonly CustomerModel _customerModel;
RelayCommand _saveCommand;
public CustomerViewModel(CustomerModel customer)
{
_customerModel = customer;
}
public string FirstName
{
get { return _customerModel.FirstName; }
set
{
_customerModel.FirstName = value;
base.OnPropertyChanged("FirstName");
}
}
public string LastName
{
get { return _customerModel.LastName; }
set
{
_customerModel.LastName = value;
base.OnPropertyChanged("LastName");
}
}
public string CustomerLog
{
get { return _customerModel.CustomerLog; }
set
{
_customerModel.CustomerLog = value;
base.OnPropertyChanged("CustomerLog");
}
}
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(param => Save(), param => CanSave);
}
return _saveCommand;
}
}
private void Save()
{
AppendToLog("I am about to save");
//Pretend we have saved the customer
AppendToLog("CustomerSaved");
}
internal void AppendToLog(string text)
{
_customerModel.CustomerLog += text + Environment.NewLine; ;
OnPropertyChanged("CustomerLog");
}
static bool CanSave
{
get
{
return true;
}
}
Where do you declare a relationship between the view
x:Class="MyCompany.CustomerStore.Views.CustomerView
and the model class CustomerViewModel?
I don't see that anywhere.
I think you need to set the DataContext of the View to the Model.

Resources