I have a single Database EstimateInformationTable with CATEGORY, DESCRIPTION. 100 records total. There are 100 Descriptions and 10 Categories, so obviously the Categories are used more than once.
example:
+----------+-------------+
| CATEGORY | DESCRIPTION |
+----------+-------------+
| ACC | DescAAAA |
| ACC | DescBBBB |
| BMX | DescCCCC |
+----------+-------------+
I want to use the first ComboBox (CATEGORY) to limit the choices in the second ComboBox (DESCRIPTION).
I have two ComboBoxes bound to two DataSet TableAdaptors. Each TableAdaptor returns a simple, but different Schema.
ComboBox1:
SELECT DISTINCT CATEGORY
FROM EstimateInformationTable
ORDER BY CATEGORY
ComboBox2:
SELECT DESCRIPTION
FROM EstimateInformationTable
WHERE (CATEGORY = #Category)
ORDER BY DESCRIPTION
I can kind of get this to work in CodeBehind using an extra ButtonClickEvent, but obviously this is not ultimately what I want.
I want to use MVVM and the correct Notify Properties (if that is what needs to be done) so that changing the Category ComboBox updates the Description ComboBox.
This must be done all the time, but I am new to a lot of this. I was making progress, but I am having a hard time wrapping my head around this. This is a self imposed learning exercise, so feel free to dumb the explanation down for me. Thanks, mike
XAML:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:gobo.Pages"
xmlns:gobo="clr-namespace:gobo" x:Class="gobo.Pages.TESTSTUFF01"
xmlns:vm="clr-namespace:gobo.ViewModel"
mc:Ignorable="d"
Title="TESTSTUFF01" Loaded="Page_Loaded">
<Page.Resources>
<vm:CategoryChangedViewModel x:Key="CategoryChangedViewModel"/>
<gobo:gobo2018DataSet1 x:Key="gobo2018DataSet1"/>
<CollectionViewSource x:Key="estimateInformationTableViewSource" Source="{Binding EstimateInformationTable, Source={StaticResource gobo2018DataSet1}}"/>
<gobo:gobo2018EstimateInformationTableDescriptionDataSet x:Key="gobo2018EstimateInformationTableDescriptionDataSet"/>
<CollectionViewSource x:Key="estimateInformationTableViewSource1" Source="{Binding EstimateInformationTable, Source={StaticResource gobo2018EstimateInformationTableDescriptionDataSet}}"/>
</Page.Resources>
<Page.Background>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="Red" Offset="1"/>
</LinearGradientBrush>
</Page.Background>
<StackPanel Orientation="Vertical" >
<Label Content="TEST STUFF 01 Tab Page1" VerticalAlignment="Top" Background="{x:Null}"/>
<Button Content="Change Description contents" Click="Button_Click"/>
<Grid x:Name="grid1" DataContext="{StaticResource estimateInformationTableViewSource}" HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="CATEGORY:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
<ComboBox x:Name="cATEGORYComboBox" Grid.Column="1" DisplayMemberPath="CATEGORY" HorizontalAlignment="Left" Height="Auto" Margin="3" Grid.Row="0" VerticalAlignment="Center" Width="120"
ItemsSource="{Binding}"
SelectedIndex="{Binding Category, Source={StaticResource CategoryChangedViewModel}}">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
</Grid>
<Grid x:Name="grid2" DataContext="{StaticResource estimateInformationTableViewSource1}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="311">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="DESCRIPTION:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0" VerticalAlignment="Center"/>
<ComboBox x:Name="dESCRIPTIONComboBox" Grid.Column="1" DisplayMemberPath="DESCRIPTION" HorizontalAlignment="Left" Height="Auto" ItemsSource="{Binding}" Margin="3,9,-53,9" Grid.Row="0" VerticalAlignment="Center" Width="180">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel/>
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
</ComboBox>
</Grid>
</StackPanel>
</Page>
CurrentCodeBehind
namespace gobo.Pages
{
/// <summary>
/// Interaction logic for TESTSTUFF01.xaml
/// </summary>
public partial class TESTSTUFF01 : Page
{
private gobo.gobo2018DataSet1 gobo2018DataSet1;
public gobo.gobo2018DataSet1TableAdapters.EstimateInformationTableTableAdapter gobo2018DataSet1TableAdapter;
private CollectionViewSource estimateInformationTableViewSource;
private gobo.gobo2018EstimateInformationTableDescriptionDataSet gobo2018EstimateInformationTableDescriptionDataSet;
private gobo.gobo2018EstimateInformationTableDescriptionDataSetTableAdapters.EstimateInformationTableTableAdapter EstimateInformationTableTableAdapter;
private CollectionViewSource estimateInformationTableViewSource1;
public TESTSTUFF01()
{
InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
gobo2018DataSet1 = ((gobo.gobo2018DataSet1)(this.FindResource("gobo2018DataSet1")));
gobo2018DataSet1TableAdapter = new gobo.gobo2018DataSet1TableAdapters.EstimateInformationTableTableAdapter();
gobo2018DataSet1TableAdapter.Fill(gobo2018DataSet1.EstimateInformationTable);
estimateInformationTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("estimateInformationTableViewSource")));
estimateInformationTableViewSource.View.MoveCurrentToFirst();
gobo2018EstimateInformationTableDescriptionDataSet = ((gobo.gobo2018EstimateInformationTableDescriptionDataSet)(this.FindResource("gobo2018EstimateInformationTableDescriptionDataSet")));
EstimateInformationTableTableAdapter = new gobo.gobo2018EstimateInformationTableDescriptionDataSetTableAdapters.EstimateInformationTableTableAdapter();
EstimateInformationTableTableAdapter.FillByCategory(gobo2018EstimateInformationTableDescriptionDataSet.EstimateInformationTable,"ACC");
estimateInformationTableViewSource1 = ((System.Windows.Data.CollectionViewSource)(this.FindResource("estimateInformationTableViewSource1")));
estimateInformationTableViewSource1.View.MoveCurrentToFirst();
}
public void LoadDescriptionToCbo(String parameter)
{
if(gobo2018EstimateInformationTableDescriptionDataSet != null)
{
EstimateInformationTableTableAdapter.FillByCategory(gobo2018EstimateInformationTableDescriptionDataSet.EstimateInformationTable, parameter);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
LoadDescriptionToCbo("ACT");
Console.WriteLine("Button Click -> LoadDescriptionToCode");
}
}
}
I've found that this works, but I am curious if it is the best answer.
private void cATEGORYComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox cbx = (ComboBox)sender;
string s = ((DataRowView)cbx.Items.GetItemAt(cbx.SelectedIndex)).Row.ItemArray[0].ToString();
LoadDescriptionToCbo(s);
}
Related
I am trying to get Drag and Drop working with WinUI3. In WPF I used to add added both AllowDrop and Drop to a UI element and I was able to receive the filename of a dropped file. However in WinUI3 the method Drop is not beeing executed. What am I doing wrong?
XAML
<Page
x:Class="..."
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="..."
xmlns:helper="..."
xmlns:prop="..."
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<DataTemplate x:Key="Image" x:DataType="helper:ProductImage">
<Border BorderBrush="{x:Bind Path=Color, Mode=OneWay}" BorderThickness="1" Background="Transparent"
AllowDrop="True" Drop="Image_Drop" >
<Grid Width="{Binding ElementName=PIImageSize, Path=Value}"
Height="{Binding ElementName=PIImageSize, Path=Value}" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Margin="2" HorizontalAlignment="Center"
Text="{x:Bind Path=Type, Mode=OneWay}"
Foreground="{x:Bind Path=Color, Mode=OneWay}" />
<Image Grid.Row="1" Stretch="Uniform" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Source="{x:Bind Path=BitmapImage, Mode=OneWay}"/>
<TextBox Grid.Row="2" Text="{x:Bind Path=Path, Mode=TwoWay}" />
</Grid>
<Border.ContextFlyout>
</Border.ContextFlyout>
</Border>
</DataTemplate>
</Page.Resources>
...
</Page>
Code
private void Image_Drop(object sender, DragEventArgs e)
{
// Function is not executed
}
You also have to add the DragOver event, to accept the operation:
private void Image_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
}
I am trying to implement a MVVM ContentPage with a ListView that needs to bind to a populated generic list of XML model objects in a ViewModel but the binding fails. The code that is shown calls an API that does return a valid list of XML data. The same code works fine when the binding is done directly in the code behind of the XAML Xamarin contentpage by setting the ItemSource in the codebehind. As said, the problem only happens when trying to pass the ListView through the ViewModel assigned to the contentpage. I have stepped through the code in the ViewModel and the ListView is populated successfully but the binding just doesn't work. I have other controls that are on the page that the model binding does work for but the only control that doesn't work is the ListView. The code is shown below:
ViewModel:
using RestDemo.Model;
using RestDemo.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using System.ComponentModel;
using System.Windows.Input;
using System.Collections.ObjectModel;
namespace RestDemo.ViewModel
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ViewModel ()
{
GetRequest();
}
List<XmlPizzaDetails> _objPizzaList;
string _selectedDescription = "Descriptions: ";
bool _progress;
string _cusButtonText = "Hello";
public bool Progress
{
get { return _progress; }
set { _progress = value; }
}
public string CusButtonText
{
get { return _cusButtonText; }
set { _cusButtonText = value; }
}
public string SelectedDescription
{
get { return _selectedDescription; }
set { _selectedDescription = value; }
}
public List<XmlPizzaDetails> ObjPizzaList
{
get { return _objPizzaList; }
set
{
if (_objPizzaList != value)
{
_objPizzaList = value;
OnPropertyChanged("ObjPizzaList");
}
}
}
public string Description
{
get { return _selectedDescription; }
set { _selectedDescription = value; }
}
public ICommand SelectedCommand => new Command(() =>
{
CusButtonText = "Goodby";
});
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
}
remove
{
}
}
public async void GetRequest()
{
if (NetworkCheck.IsInternet())
{
Uri geturi = new Uri("http://api.androidhive.info/pizza/?format=xml"); //replace your xml url
HttpClient client = new HttpClient();
HttpResponseMessage responseGet = await client.GetAsync(geturi);
string response = await responseGet.Content.ReadAsStringAsync();
//Xml Parsing
ObjPizzaList = new List<XmlPizzaDetails>();
XDocument doc = XDocument.Parse(response);
foreach (var item in doc.Descendants("item"))
{
XmlPizzaDetails ObjPizzaItem = new XmlPizzaDetails();
ObjPizzaItem.ID = item.Element("id").Value.ToString();
ObjPizzaItem.Name = item.Element("name").Value.ToString();
ObjPizzaItem.Cost = item.Element("cost").Value.ToString();
ObjPizzaItem.Description = item.Element("description").Value.ToString();
ObjPizzaList.Add(ObjPizzaItem);
}
Progress = false;
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
}
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xlocal="clr-namespace:RestDemo.ViewModel"
xmlns:local="clr-namespace:RestDemo"
xmlns:Views="clr-namespace:RestDemo.Views"
x:Class="RestDemo.XmlParsingPageBehavior">
<ContentPage.BindingContext>
<xlocal:ViewModel />
</ContentPage.BindingContext>
<Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Views:CustomButton Grid.Row="0" Grid.Column="0" Text="HOME" />
<Views:CustomButton Grid.Row="0" Grid.Column="1" Text="Administrative Maintence" />
<Views:CustomButton Grid.Row="0" Grid.Column="2" Text="User Maintence" />
<Views:CustomButton Grid.Row="0" Grid.Column="3" Text="About" />
</Grid>
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Views:CustomButton Grid.Row="0" Grid.Column="0" Text="{Binding CusButtonText, Mode=TwoWay}">
<Views:CustomButton.Behaviors>
<local:ItemSelectedToCommandBehavior />
</Views:CustomButton.Behaviors>
</Views:CustomButton>
</Grid>
<Frame Margin="5, 5, 5, 5" Grid.Row="2" Grid.Column="1" BackgroundColor = "Cyan">
<ListView x:Name="PizzaListView" ItemsSource="{Binding ObjPizzaList}" Margin="5, 0, 5, 0" Grid.Row="2" Grid.Column="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid HorizontalOptions="FillAndExpand" Margin="0,0,0,0" Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Text="{Binding Name}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue" FontAttributes="Bold"/>
<Label Text="{Binding Cost}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange" FontAttributes="Bold"/>
<Label Text="{Binding Description}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray" FontAttributes="Bold"/>
<BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="Fill" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Frame>
</Grid>
<ActivityIndicator x:Name="ProgressLoader" IsVisible="{Binding Progress}" IsRunning="True"/>
</Grid>
</ContentPage>
I have it working. Yes ObservableCollections are the way to go but generic Lists are fine as well. The problem is that when the Model is bound the WebService call has not completed so when the List property is bound it is still null. Even when updated at this point the ObservableCollection won't work because it has not been seeded. The solution is to seed the ObservableCollection, or List, on the Page's OnAppearing event and bind the ViewModel as the BindingContext in this event. My solution is below:
protected override async void OnAppearing()
{
var vm = new ViewModel.ViewModel();
if (vm == null)
return;
HttpClient client = new HttpClient();
HttpResponseMessage responseGet = await client.GetAsync(vm.Geturi);
string response = await responseGet.Content.ReadAsStringAsync();
//Xml Parsing
var _objPizzaList = new ObservableCollection<XmlPizzaDetails>();
XDocument doc = XDocument.Parse(response);
vm.GetRequest(doc);
this.BindingContext = vm;
}
I have view with a combobox and five textboxes which is used to add new customer. To add the customer, declared the properties in my viewmodel and bind those properties to all respective textboxes text properties like,
View:
<StackPanel>
<ComboBox ItemsSource="{Binding Customers}" SelectedItem="{Binding SelectedCustomers}" DisplayMemberPath="Name"/>
<Textbox Text="{Binding Name}"/>
<Textbox Text="{Binding Age}"/>
<Textbox Text="{Binding Phone}"/>
<Textbox Text="{Binding Address}"/>
<Textbox Text="{Binding Email}"/>
<StackPanel>
ViewModel:
public class myviewmodel
{
private string _name;
public string Name
{
get { return _name;}
set { _name = value; OnPropertyChanged("Name"); }
}
private string _age;
public string Age
{
get { return _age;}
set { _age = value; OnPropertyChanged("Age"); }
}
private Customer _selectedCustomer;
public Customer SelectedCustomer
{
get { return _selectedCustomer; }
set { selectedCustomer = value; OnPropertyChanged("SelectedCustomer"); }
}
}
I will load the existing customer names to the comboxbox. To update the existing
customer details, if i select a customer name in combobox the selected customer details
should bind in textboxes so that i can easily update them. but the textbox text
properties are already used to add the new customers. so how to add and update the
customers using the same textboxes??
The Textboxes' Bindings are not set to the SelectedCustomer. Give this a try.
<ComboBox ItemsSource="{Binding Customers}" SelectedItem="{Binding SelectedCustomer}" DisplayMemberPath="Name"/>
<Grid Visibility="{Binding ExistingCustomer, Converter={StaticResource VisibilityConverter}}">
<Textbox Text="{Binding SelectedCustomer.Name, Mode=TwoWay}"/>
<Textbox Text="{Binding SelectedCustomer.Age, Mode=TwoWay}}"/>
<Textbox Text="{Binding SelectedCustomer.Phone, Mode=TwoWay}}"/>
<Textbox Text="{Binding SelectedCustomer.Address, Mode=TwoWay}}"/>
<Textbox Text="{Binding SelectedCustomer.Email, Mode=TwoWay}}"/>
</Grid>
<Grid Visibility="{Binding ExistingCustomer, Converter={StaticResource VisibilityConverter}}">
<Textbox Text="{Binding Customer.Name, Mode=TwoWay}"/>
<Textbox Text="{Binding Customer.Age, Mode=TwoWay}}"/>
<Textbox Text="{Binding Customer.Phone, Mode=TwoWay}}"/>
<Textbox Text="{Binding Customer.Address, Mode=TwoWay}}"/>
<Textbox Text="{Binding Customer.Email, Mode=TwoWay}}"/>
</Grid>
And here is the code for the converter
public class VisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string culture)
{
bool displayControl = (bool)value;
if (displayControl == true)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, string culture)
{
return null;
}
}
Be sure to reference the namespace where your converter lives in your page resources
Using Interaction Behaviors this can be achieved.
First of all, the Behaviors SDK is not built-in UWP, but has to be downloaded separately from NuGet.
You can use the following command to install it:
Install-Package Microsoft.Xaml.Behaviors.Uwp.Managed
Or just use the NuGet Package Manager and search for Microsoft.Xaml.Behaviors.Uwp.Managed.
After you install, you can just add the XAML using statements to the top of your page:
<Page ...
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core" />
You do not need to create another property SelectedCustomer if you are always going to bind your TextBox from Combobox SelectedItem. Unless you intend to use SelectedCustomer for some other code behind work.
Below is how you achieve your TextBox Text without SelectedCustomer Property.
<ComboBox x:Name="comboBox" ItemsSource="{Binding Customers}" DisplayMemberPath="Name" HorizontalAlignment="Stretch" Margin="5,0">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding SelectedItem, ElementName=comboBox}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</ComboBox>
<StackPanel Orientation="Vertical" Grid.Row="1" Margin="5,20" DataContext="{Binding SelectedItem, ElementName=comboBox}">
<TextBox Text="{Binding Name, Mode=TwoWay}" PlaceholderText="Name" Name="Name"/>
<TextBox Text="{Binding Age, Mode=TwoWay}" PlaceholderText="Age" Name="Age"/>
<TextBox Text="{Binding Phone, Mode=TwoWay}" PlaceholderText="Phone" Name="Phone"/>
<TextBox Text="{Binding Address, Mode=TwoWay}" PlaceholderText="Address" Name="Address"/>
<TextBox Text="{Binding Email, Mode=TwoWay}" PlaceholderText="Email" Name="Email"/>
</StackPanel>
If you notice, I bound the data from comboBox SelectedItem Property to StackPanel DataContext and then Individual Properties directly to Text of your TextBox. This will take care of your ComboBox Binding to TextBox. Mode should always be TwoWay so that data can be updated when user Modifies Existing Customer Details.
Now after this is done, When you want to add a new Customer Info with current TextBoxes, You want to clear the selection without changing the current value. Below is how I added a Button with Interaction Behaviors.
And use the Clicked action to clear the TextBox Text. In UWP XAML you can use empty string as value and it works as expected.
<Button Content="+" Grid.Column="1" Margin="5,0" Tag="{Binding EmptyClass, Mode=TwoWay}" Name="btnNew">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Click">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding Tag, ElementName=btnNew, Mode=TwoWay}" />
<core:ChangePropertyAction TargetObject="{Binding ElementName=comboBox}" PropertyName="SelectedIndex" Value="-1" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</Button>
Also Note I am making the selected Index of ComboBox to -1 so that selected Data cannot be updated.
And now the saving portion should be pretty simple and straight forward. Below is a button that i used with TappedEvent
private void saveBtn_Tapped(object sender, TappedRoutedEventArgs e)
{
model.Customers.Add(model.EmptyClass);
model.EmptyClass = new MyClass();
}
You can see I am reinstantiating EmptyClass Again so that old bound data can be cleared off.
Below is Complete XAML
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App15"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Text="using:System.Text"
x:Class="App15.MainPage"
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"
Loaded="Page_Loaded"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid Margin="0,100,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="comboBox" ItemsSource="{Binding Customers}" DisplayMemberPath="Name" HorizontalAlignment="Stretch" Margin="5,0">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding SelectedItem, ElementName=comboBox}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</ComboBox>
<Button Content="+" Grid.Column="1" Margin="5,0" Tag="{Binding EmptyClass, Mode=TwoWay}" Name="btnNew">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Click">
<core:ChangePropertyAction TargetObject="{Binding ElementName=stkData}" PropertyName="DataContext" Value="{Binding Tag, ElementName=btnNew, Mode=TwoWay}" />
<core:ChangePropertyAction TargetObject="{Binding ElementName=comboBox}" PropertyName="SelectedIndex" Value="-1" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</Button>
</Grid>
<StackPanel Orientation="Vertical" Grid.Row="1" Margin="5,20" Name="stkData">
<TextBox Text="{Binding Name, Mode=TwoWay}" PlaceholderText="Name"/>
<TextBox Text="{Binding Age, Mode=TwoWay}" PlaceholderText="Age" />
<TextBox Text="{Binding Phone, Mode=TwoWay}" PlaceholderText="Phone" />
<TextBox Text="{Binding Address, Mode=TwoWay}" PlaceholderText="Address" />
<TextBox Text="{Binding Email, Mode=TwoWay}" PlaceholderText="Email" />
</StackPanel>
<Button Name="saveBtn" Content="Save" HorizontalAlignment="Stretch" Margin="5" Grid.Column="1" Grid.Row="2" Tapped="saveBtn_Tapped"/>
</Grid>
</Grid>
</Page>
Below is Complete Code Behind
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
namespace App15
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
MyViewModel model = new MyViewModel();
private void Page_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = model;
}
private void saveBtn_Tapped(object sender, TappedRoutedEventArgs e)
{
model.Customers.Add(model.EmptyClass);
model.EmptyClass = new MyClass();
}
}
}
Below is Complete View Model
public class MyViewModel
{
public MyViewModel()
{
Customers = new ObservableCollection<MyClass>();
EmptyClass = new MyClass();
for (int i = 0; i < 10; i++)
{
Customers.Add(new MyClass()
{
Name = "Item" + (i + 1).ToString(),
Address = "Address" + (i + 1).ToString(),
Age = "20" + (i + 1).ToString(),
Email = "Test" + (i + 1).ToString() + "#test.com",
Phone = (9876543210 + i).ToString()
});
}
}
public ObservableCollection<MyClass> Customers { get; set; }
public MyClass EmptyClass { get; set; }
}
public class MyClass
{
public string Name { get; set; }
public string Age { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Email { get; set; }
}
I know there is a way to even use Save Option in MVVM But I did not get the opportunity to use DelegateCommand. But if you would like to try it yourself, Check this Video by Jerry Nixon for Reference
Binding Data to Grid View finding it difficult
if (response.StatusCode == HttpStatusCode.OK)
{
List<dashboard1> variable1 = new List<dashboard1>();
var jsonString = await response.Content.ReadAsStringAsync();
dynamic arr = JsonParser.Parse(jsonString);
var items2 = arr[0].items;
foreach (var item3 in items2)
{
variable1.Add(item3.sectionName);
variable1.Add(item3.procedureName);
variable1.Add(item3.reportName);
variable1.Add(item3.templateName);
}
itemGridView.ItemsSource = variable1;
}
parsed json and stored it in list
now i don't know how to bind these values to User Interface please can u help me to continue and pass values to Grid view .
You have to bind properties of class dashboard1 with the UI controls. Suppose you are showing all the properties , in TextBlock then bind textbox's text property with property of class dashboard1.
So code will be like this.
<TextBlock Text={Binding sectionName} />
<GridView Grid.Row="2"
x:Name="itemGridView"
SelectionMode="Multiple"
SelectionChanged="itemGridView_SelectionChanged" >
<GridView.ItemTemplate >
<DataTemplate >
<Border BorderThickness="1" BorderBrush="#7b579b" Tapped="Border_Tapped_1" >
<Grid Name="tile" Background="{Binding SubjectTilebackGround}" Height="150" Width="150" Tapped="tile_Tapped_1" >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock x:Name="hello2" Text="{Binding SubjectName}" Foreground="White" FontSize="15" Grid.Row="0" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="8" FontWeight="ExtraLight" Visibility="{Binding isTopSubjectTextVisible}"/>
<TextBlock Text="{Binding SubjectName}" Foreground="White" FontSize="15" Grid.Row="1" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="8" FontWeight="ExtraLight" Visibility="{Binding isBottomSubjectTextVisible}" />
</Grid>
</Border>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal" Margin="98,0,0,0"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate >
<DataTemplate >
<Grid Margin="0,0,0,6" >
<Button
AutomationProperties.Name="Group Title"
Style="{StaticResource TextPrimaryButtonStyle}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding CategoryName}" Margin="2" FontSize="30" Foreground="White" FontWeight="Light" />
<TextBlock Text="( 17 Apps )" Margin="10,2,2,2" FontSize="25" Foreground="White" FontWeight="ExtraLight" VerticalAlignment="Bottom" />
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,80,0" MaximumRowsOrColumns="3" />
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</GridView.GroupStyle>
</GridView>
in this example i have added some more useful properties of gridview..and wherever i have used binding like this.
Background="{Binding SubjectTilebackGround}"
it means "SubjectTilebackGround" is a property present in the class of which objects you have made your list ..means in your case is is DASHBOARD1..so any properties available in your dashboard that you can bind them as i did. hope this will help.
I'm relatively new at WPF and C#. Following this example, I have created a form with a datagrid and two comboboxes (FileName and PartID) that I'd like to use to filter the datagrid (surveyresponsesDataGrid).
Here is my XAML for the WPF Form:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dat="clr-namespace:System.Windows.Data;assembly=PresentationFramework"
Title="Review Data" Height="446" Width="987" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:my="clr-namespace:SWA_IFR" Loaded="Window_Loaded">
<Window.Resources>
<CollectionViewSource
Source="{Binding ElementName=surveyresponses, Path=FileName.SelectedItem}"
x:Key="cvs" Filter="fn_Filter"
x:Name="srView"
CollectionViewType="{x:Type dat:ListCollectionView}" />
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False" EnableRowVirtualization="True" Height="247" HorizontalAlignment="Left"
ItemsSource="{Binding Source={StaticResource cvs}}" Margin="12,93,0,0" Name="surveyresponsesDataGrid"
RowDetailsVisibilityMode="VisibleWhenSelected" VerticalAlignment="Top" Width="941">
<DataGrid.Columns>
<DataGridTextColumn x:Name="fileUploadNameColumn" Binding="{Binding Path=FileUploadName}" Header="File Upload Name" Width="*" />
<DataGridTextColumn x:Name="participantIDColumn" Binding="{Binding Path=ParticipantID}" Header="Participant ID" Width="*" />
<DataGridTextColumn x:Name="quesIDColumn" Binding="{Binding Path=QuesID}" Header="Ques ID" Width="*" />
<DataGridTextColumn x:Name="quesTypeColumn" Binding="{Binding Path=QuesType}" Header="Ques Type" Width="*" />
<DataGridTextColumn x:Name="scoreIntColumn" Binding="{Binding Path=ScoreInt}" Header="Score Int" Width="*" />
<DataGridTextColumn x:Name="scoreTextColumn" Binding="{Binding Path=ScoreText}" Header="Score Text" Width="*" />
<DataGridTextColumn x:Name="scoreDescrColumn" Binding="{Binding Path=ScoreDescr}" Header="Score Descr" Width="*" />
</DataGrid.Columns>
</DataGrid>
<ComboBox Height="29" HorizontalAlignment="Left" Margin="184,17,0,0" Name="FileName" VerticalAlignment="Top" Width="211" SelectionChanged="FileName_SelectionChanged" />
<Label Content="Filter by File Upload Name" Height="29" HorizontalAlignment="Left" Margin="14,17,0,0" Name="label2" VerticalAlignment="Top" Width="159" />
<ComboBox Height="29" HorizontalAlignment="Left" Margin="184,52,0,0" Name="PartID" VerticalAlignment="Top" Width="211" />
<Label Content="Filter by Participant ID" Height="29" HorizontalAlignment="Left" Margin="14,52,0,0" Name="label1" VerticalAlignment="Top" Width="159" />
</Grid>
Here is my code:
public partial class ReviewData : Window
{
SMEntities context = new SMEntities();
public ReviewData()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var filename = context.surveyresponses.Select(f => f.FileUploadName).Distinct();
this.FileName.ItemsSource = filename;
var partid = context.surveyresponses.Select(p => p.ParticipantID).Distinct();
this.PartID.ItemsSource = partid;
}
void fn_Filter(object sender, FilterEventArgs e)
{
if (e.Item is surveyresponse)
e.Accepted = (e.Item as surveyresponse).FileUploadName.ToUpper().Contains(FileName.Text.ToUpper());
else
e.Accepted = true;
}
private void RefreshList()
{
if (surveyresponsesDataGrid.Items is CollectionView)
{
CollectionViewSource csv = (CollectionViewSource)FindResource("cvs");
if (csv != null)
csv.View.Refresh();
}
}
private void srFilter_TextChanged(object sender, TextChangedEventArgs e)
{
RefreshList();
}
} }
First problem is that I don't think the CollectionViewSource is correctly setup in the Window.Resource section, but I can't find any clear guidance about what's off. The EF class is surveyresponses but not sure that the I've correctly set the Path attribute -- currently it is set to the SelectedItem of the first combobox FileName. My goal is to filter the datagrid for only the entries that match the selection in the FileName combobox.
Second problem is that I'm uncertain how I would go about having a secondary filter, such that once the first filter is set, that selecting the PartId combobox will further filter the datagrid based on the second field (Participant ID).
I'm missing something fundamental and don't see what it is.
Thanks for the guidance.