c# UWP ListView with Columns Binding Sqlite - c#

I am trying a ListView with multiple columns, with my code I get that, but i got some problem with the binding code, because I am geting the same values in both columns.
How I can get this?
MainPage.xaml
<Page
x:Class="SQlite_Test_01.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SQlite_Test_01"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button x:Name="btnCreateDB" Content="Crear DataBase" HorizontalAlignment="Left" Margin="23,10,0,0" VerticalAlignment="Top" Height="83" Width="255" Click="btnCreateDB_Click"/>
<Button x:Name="btnFillList" Content="Llenar Lista 1" HorizontalAlignment="Left" Margin="295,10,0,0" VerticalAlignment="Top" Height="83" Width="299" Click="btnFillList_Click"/>
<ListView x:Name="ctlList" Margin="23,113,0,241" BorderBrush="Black" BorderThickness="1" Background="White" HorizontalAlignment="Left" Width="944" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid Width="{Binding ElementName=ctlList , Path=ActualWidth }" Padding="0" Margin="0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="300" />
<ColumnDefinition Width="000" />
</Grid.ColumnDefinitions>
<TextBox x:Name="Col1" Text="{Binding}" Grid.Column="0" TextWrapping="Wrap" />
<TextBox x:Name="Col2" Text="{Binding}" Grid.Column="1" TextWrapping="Wrap" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<ListBox x:Name="ctlList_2" Margin="1047,113,0,241" BorderBrush="Black" BorderThickness="1" Background="White" HorizontalAlignment="Left" Width="155" ScrollViewer.IsVerticalScrollChainingEnabled="True" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Width="{Binding ActualWidth, ElementName=ctlList_2}" Padding="0" Margin="0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="0" />
<ColumnDefinition Width="0" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding}" Grid.Column="0" TextWrapping="Wrap" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Page>
MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using SQLitePCL;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace SQlite_Test_01
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
public SQLitePCL.SQLiteConnection dbConnection = new SQLiteConnection("folders.db");
private void btnCreateDB_Click(object sender, RoutedEventArgs e)
{
SQLiteConnection dbConnection = new SQLiteConnection("folders.db");
string sSQL = #"CREATE TABLE IF NOT EXISTS Folders
(IDFolder Integer Primary Key Autoincrement NOT NULL
, Foldername VARCHAR ( 200 )
, Path VARCHAR ( 255 ));";
ISQLiteStatement cnStatement = dbConnection.Prepare(sSQL);
cnStatement.Step();
}
private void btnFillList_Click(object sender, RoutedEventArgs e)
{
var items1 = new List<String>();
var items2 = new List<String>();
string sSQL = #"SELECT [Foldername],[Path] FROM Folders";
ISQLiteStatement dbState = dbConnection.Prepare(sSQL);
while (dbState.Step() == SQLiteResult.ROW)
{
string sFoldername = dbState["Foldername"] as string;
string sPath = dbState["Path"] as string;
items1.Add(sFoldername);
items2.Add(sPath);
;
}
ctlList.ItemsSource = items1;
ctlList_2.ItemsSource = items2;
}
}
}
PD: ctlList_2 will be erased when I resolve my trouble.

I am trying a ListView with multiple columns, with my code I get that, but i got some problem with the binding code, because I am geting the same values in both columns. How I can get this?
First, create a new class called Folders:
public class Folders
{
public string Foldername { get; set; }
public string Path { get; set; }
}
Then, set the ItemsSource for ctlList with List<Folders> instead of List<string>:
private void btnFillList_Click(object sender, RoutedEventArgs e)
{
// set the ItemsSource for ctlList with List<Folders> instead of List<string>:
var items1 = new List<Folders>();
string sSQL = #"SELECT [Foldername],[Path] FROM Folders";
ISQLiteStatement dbState = dbConnection.Prepare(sSQL);
while (dbState.Step() == SQLiteResult.ROW)
{
string sFoldername = dbState["Foldername"] as string;
string sPath = dbState["Path"] as string;
Folders folder = new Folders() { Foldername = sFoldername, Path = sPath };
items1.Add(folder);
;
}
ctlList.ItemsSource = items1;
}
Last, bind Foldername and Path to different columns:
<DataTemplate>
<Grid Width="{Binding ElementName=ctlList , Path=ActualWidth }" Padding="0" Margin="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="300" />
<ColumnDefinition Width="000" />
</Grid.ColumnDefinitions>
<TextBox x:Name="Col1" Text="{Binding Path=Foldername}" Grid.Column="0" TextWrapping="Wrap" />
<TextBox x:Name="Col2" Text="{Binding Path=Path}" Grid.Column="1" TextWrapping="Wrap" />
</Grid>
</DataTemplate>
Here is Entire Sample for your reference.

Related

Where do File Parsers belong in MVVM Design Pattern?

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.

ScrollViewer ChangeView on SizeChanged

I have DataTemplate which I use in HubSection:
<DataTemplate x:Name="dataTemplate2">
<Grid x:Name="greedy">
<ScrollViewer x:Name="scroller" SizeChanged="ScrollViewer_SizeChanged" Height="{Binding Height,ElementName=greedy}" >
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource dataTemplateDetails}">
<ItemsControl.ItemContainerTransitions>
<TransitionCollection>
<ReorderThemeTransition />
<NavigationThemeTransition />
</TransitionCollection>
</ItemsControl.ItemContainerTransitions>
</ItemsControl>
</ScrollViewer>
</Grid>
</DataTemplate>
In my ItemsControl I have items which can be expandable. What I want to achieve is that when the item will expand to see more details about that item. I want Scrollviewer to scroll down (for amount of changed size of ScrollViewer).
Code behind for SizeChanged event:
private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
{
ScrollViewer myScroll = (ScrollViewer)sender;
myScroll.ChangeView(null, myScroll.ScrollableHeight, null, false);
}
What I have done now is not working as my expectation. I scroll down to the end right now. But the thing is it scrolls only when the items extend the size of available view (ScrollBar is shown). Then if I expand another item it doesn't work. If I hide details about item (ScrollBar hides too) and expand it again it will work again.
It's like the SizeChanged event occures only when ScrollViewer is going into action but have infinite height which doesn't change.
I've tried Grid with row set to "*", it changes nothing. Now I try to set height by binding it to height of ItemsControl - still the same behaviour.
Could you help me with the solution, show the path of thinking or enlighten me with some workaround?
EDIT:
I prepared some code to work with to see what happens exactly.
1) Create New Project -> Store Apps (c#) -> Windows Phone 8.1 (Blank App) and name it "scroll"
2) Paste this code into MainPage.xaml
<Page
x:Class="scroll.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:scroll"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="DarkOliveGreen">
<Page.Resources>
<DataTemplate x:Name="dataTemplateDetails">
<Grid Name="grido" Grid.Row="1" Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="Auto" />
<RowDefinition Height="50" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<Border Grid.Row="0" Background="Black" CornerRadius="10" Opacity="0.4" />
<Border Grid.Row="1" Background="Black" CornerRadius="10" Opacity="0.3" />
<Border Grid.Row="2" Background="Black" CornerRadius="10" Opacity="0.2" />
<Border Grid.Row="3" Background="Black" CornerRadius="10" Opacity="0.1" />
<TextBlock Grid.Row="0" Text="{Binding Name}" Style="{StaticResource BaseTextBlockStyle}" HorizontalAlignment="Center"/>
<Grid Grid.Row="1" HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="5,0,5,0" Text="Description:" Style="{StaticResource BaseTextBlockStyle}"/>
<TextBlock Grid.Column="1" Text="{Binding Description}" Style="{StaticResource BaseTextBlockStyle}"/>
</Grid>
<TextBlock Grid.Row="2" Text="Next row" Style="{StaticResource BaseTextBlockStyle}" HorizontalAlignment="Center"/>
<TextBlock Grid.Row="3" Text="Next row" Style="{StaticResource BaseTextBlockStyle}" HorizontalAlignment="Center"/>
</Grid>
</DataTemplate>
<DataTemplate x:Name="dataTemplate2">
<Grid x:Name="greedy" >
<ScrollViewer x:Name="scroller" SizeChanged="ScrollViewer_SizeChanged" VerticalAlignment="Top">
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource dataTemplateDetails}">
<ItemsControl.ItemContainerTransitions>
<TransitionCollection>
<ReorderThemeTransition />
<NavigationThemeTransition />
</TransitionCollection>
</ItemsControl.ItemContainerTransitions>
</ItemsControl>
</ScrollViewer>
</Grid>
</DataTemplate>
</Page.Resources>
<Page.BottomAppBar>
<CommandBar Background="Black" Opacity="0.6" x:Name="myCommandBar">
<AppBarButton Icon="Add" Label="Add" x:Name="AddItem" Click="Add_Click"/>
<AppBarButton Icon="Delete" Label="Delete" x:Name="RemoveItem" Click="Delete_Click"/>
</CommandBar>
</Page.BottomAppBar>
<Grid>
<Hub x:Name="myHub" Header="Test">
<HubSection x:Uid="myDetailsHubsection" x:Name="myDetailsHubsection" Header="Details" DataContext="{Binding Items}" ContentTemplate="{StaticResource dataTemplate2}" />
</Hub>
</Grid>
3) Paste this code into MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace scroll
{
public sealed partial class MainPage : Page
{
public static Details dataContextItems;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
dataContextItems = new Details();
}
public class TestItem
{
public string Name { get; set; }
public string Description { get; set; }
public TestItem(string n, string d)
{
Name = n;
Description = d;
}
}
public class Details : INotifyPropertyChanged
{
private ObservableCollection<TestItem> _items;
public ObservableCollection<TestItem> Items
{
set
{
_items = value;
NotifyPropertyChanged("Items");
}
get
{
return _items;
}
}
public Details()
{
_items = new ObservableCollection<TestItem>();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = dataContextItems;
}
private void Add_Click(object sender, RoutedEventArgs e)
{
TestItem iAmAnItem = new TestItem("Name of an item", "Long and detailed description of an item");
dataContextItems.Items.Add(iAmAnItem);
}
private void Delete_Click(object sender, RoutedEventArgs e)
{
if (dataContextItems.Items.Count > 0)
dataContextItems.Items.RemoveAt(0);
}
private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
{
ScrollViewer myScroll = (ScrollViewer)sender;
myScroll.ChangeView(null, myScroll.ScrollableHeight, null, false);
}
}
}
4) Run the app
5) When you add first two items you can't scroll them but when you add more items you can see that it scrolls down as soon as items "need more space" to be shown and scrollbar occures. But with adding more items it doesn't work. If you delete items and add "third" item again it will scroll down.
I want it to scroll down everytime size of scrollviewer changes (in this case when new item occures but keep in mind it should work when item "extends" in my original solution and there can be few extended items simultaneously).
I've been tinkering with the solution and I finally found a way to do that.
I think the problem is that I didn't understand how ScrollViewer does work. I took the scrolling height as UIElement height hoping for SizeChanged to be fired what isn't truth. ScrollViewer wasn't changing its size because it just took the whole space it could and then just displayed how much content it is in it (It's like ScrollViewer has almost always infinite height unless it's less than actual available view space). With adding first two items SizeChanged event was firing with third one too and then nothing happend. It proves that.
I needed SizeChanged to be fired everytime the size of ScrollViewer (or in this case the Grid) was changing. Solution is very simple but still it needs understanding of how ScrollViewer works - and now it seems so obvious that it will never be greater than available space.
Changes made to make it work:
<DataTemplate x:Name="dataTemplate2">
<ScrollViewer x:Name="scroller" VerticalAlignment="Top" HorizontalAlignment="Stretch" IsEnabled="True" >
<Grid VerticalAlignment="Top" x:Name="greedo" SizeChanged="greedo_SizeChanged">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource dataTemplateDetails}">
<ItemsControl.ItemContainerTransitions>
<TransitionCollection>
<ReorderThemeTransition />
<NavigationThemeTransition />
</TransitionCollection>
</ItemsControl.ItemContainerTransitions>
</ItemsControl>
</Grid>
</ScrollViewer>
</DataTemplate>
and code behind:
private void greedo_SizeChanged(object sender, SizeChangedEventArgs e)
{
Grid takingScroll = (Grid)sender;
ScrollViewer myScroll = (ScrollViewer)takingScroll.Parent;
myScroll.ChangeView(null, myScroll.ScrollableHeight, null, false);
}

How to get clicked item from LongListSelector? (WP8)

I have a LongListSelector that is binded with ObservableCollection of some kind of Items. Items have many different properties.
<LongListSelector Name="DraftControl" MouseLeftButtonDown="GoToEditDraft">
<LongListSelector.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
<LongListSelector.ItemTemplate>
</LongListSelector>
It has an event handler. But it gets as sender the whole LongListSelector, not a particular item. How to add event handler for all items?
Here is a handler's code:
private void GoToEditDraft(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
var clickerdItem = (LongListSelector)sender;
MessageBox.Show(clickedItem.SelectedItem.ToString());
}
So, trying to get SelectedItem this way throws NullReferenceException.
Data template:
<DataTemplate>
<Grid Margin="10" toolkit:TiltEffect.IsTiltEnabled="True">
<Grid.Background>
<SolidColorBrush Color="LightGray" Opacity="0.8"/>
</Grid.Background>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition MaxHeight="100"/>
<RowDefinition MaxHeight="30"/>
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" FontSize="28" Foreground="{StaticResource CustomApplicationTextBrush}" Text="{Binding Title, Converter={StaticResource SanitizeString}}" Margin="10,10,10,0" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2"/>
<Image Source="/Images/no-image.png" Stretch="UniformToFill" MaxHeight="100" Margin="10,10,0,10" Grid.RowSpan="1" Grid.Column="0" Grid.Row="1" VerticalAlignment="Top"/>
<TextBlock TextWrapping="Wrap" FontSize="18" Foreground="{StaticResource CustomApplicationTextBrush}" TextTrimming="WordEllipsis" Text="{Binding Address, Converter={StaticResource SanitizeString}}" Margin="10,0,10,10" Grid.Column="1" Grid.Row="1" VerticalAlignment="Top"/>
</Grid>
</DataTemplate>
Binding:
ObservableCollection<Item> draftItems = new ObservableCollection<Item>();
var draftStorage = IsolatedStorageFile.GetUserStoreForApplication();
IReadOnlyList<StorageFile> allDrafts = await draftFolder.GetFilesAsync();
foreach (StorageFile file in allDrafts)
{
using (var stream = new IsolatedStorageFileStream("Drafts\\" + file.Name, FileMode.Open, draftStorage))
{
var fileReader = new StreamReader(stream);
string jsonContents = fileReader.ReadLine();
Item readedItem = JsonConvert.DeserializeObject<Item>(jsonContents);
draftItems.Add(readedItem);
fileReader.Close();
}
}
DraftControl.ItemsSource = draftItems;
Try this.
private void DraftControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var myItem = ((Item)(sender as LongListSelector).SelectedItem);
}
Subscribe to LongListSelectors SelectionChangedEvent rather
<LongListSelector Name="DraftControl" SelectionChanged="lls_SelectionChanged">
<LongListSelector.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
<LongListSelector.ItemTemplate>
</LongListSelector>
and get the item in the code behind
private void lls_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var myItem = ((LongListSelector) sender).SelectedItem as Type;
}

Windows Phone App Crashes on ListPicker Selected Item

My (first) Windows Phone app keeps crashing when the code takes the selection from a ListPicker, and a webbrowser navigates to that selection. It builds without errors, but crashed when I run it and press the button. I am a beginner when it comes to coding, so please dumb-down your answers :)
Heres my code:
XAML:
<phone:PhoneApplicationPage
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
x:Class="SecurityCamera.Page1"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d"
shell:SystemTray.IsVisible="True">
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Name="ListPickerItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="10 0 0 0"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Name="ListPickerFullModeItemTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" Margin="10 0 0 0"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Security Camera Access" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="Specify IP" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Margin="12,138,12,0" Grid.RowSpan="2" Opacity="0.99">
<TextBox x:Name="box1" HorizontalAlignment="Left" Height="70" Margin="31,172,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box2" HorizontalAlignment="Left" Height="70" Margin="31,242,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box3" HorizontalAlignment="Left" Height="70" Margin="31,312,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<TextBox x:Name="box4" HorizontalAlignment="Left" Height="70" Margin="31,382,0,0" TextWrapping="Wrap" Text="Http://" VerticalAlignment="Top" Width="400"/>
<Button Content="Connect" HorizontalAlignment="Left" Height="80" Margin="84,527,0,0" VerticalAlignment="Top" Width="305" Click="Button_Click_1"/>
<Button Content="Save" HorizontalAlignment="Left" Height="80" Margin="84,457,0,0" VerticalAlignment="Top" Width="305" Click="Button_Click_2"/>
<TextBlock HorizontalAlignment="Left" Margin="10,119,0,0" TextWrapping="Wrap" Text="Write IP's below to save - Include http:// before all addresses!" VerticalAlignment="Top"/>
</Grid>
<toolkit:ListPicker x:Name="defaultPicker" SelectionChanged="OnListPickerChanged" ExpansionMode="FullScreenOnly" Header="Saved IP's:" Margin="72,0,72,489" Grid.Row="1"/>
<phone:WebBrowser x:Name="webBrowser" HorizontalAlignment="Left" Margin="12,143,0,0" VerticalAlignment="Top" Width="456" Grid.RowSpan="2" Height="615" Opacity="100" Visibility="Visible"/>
</Grid>
</phone:PhoneApplicationPage>
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 System.Xml;
using System.IO.IsolatedStorage;
using System.IO;
namespace SecurityCamera
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
webBrowser.Visibility = System.Windows.Visibility.Collapsed;
// DEBUG MESSAGE - DELETE
MessageBox.Show("Visibility set to Collapsed (startup)");
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
------------------------THIS IS WHERE IT CRASHES --------------------------
//DEBUG MESSAGE - DELETE
MessageBox.Show("Button Pressed!");
string selectedItem;
selectedItem = (sender as ListPicker).SelectedItem.ToString();
// Do what you want with selectedItem
webBrowser.Navigate(new Uri(selectedItem));
//DEBUG MESSAGE - DELETE
MessageBox.Show("webBrowser.Navigate Executed...Making Visible");
webBrowser.Visibility = System.Windows.Visibility.Visible;
// DEBUG MESSAGE - DELETE
MessageBox.Show("webBrowser navigation sent - webBrowser Visibility set to Visible - Button Press");
}
private void OnListPickerChanged(object sender, SelectionChangedEventArgs e)
{
string selectedItem;
selectedItem = (sender as ListPicker).SelectedItem.ToString();
// Do what you want with selectedItem
// webBrowser.Navigate(new Uri(selectedItem));
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
// Write Text's into param
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
//create new file
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("ip1.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))
{
string someTextData = "{ box1.Text }";
writeFile.WriteLine(someTextData);
writeFile.Close();
}
}
}
}
I believe this cast is failing:
selectedItem = (sender as ListPicker).SelectedItem.ToString();
instead try:
selectedItem = defaultPicker.SelectedItem.ToString();

Access the value of button and checkbox of an XAML in other another class in a wpf c# application

I'm working on a WPF Kinect project. It's one of the developer toolkit samples of Windows Kinect and it's called "Kinect Explorer". You can download it from the Kinect Developer Toolkit SDK ver 1.5. In kinectwindow.xaml I added a button and a checkbox. Also, there is a class called kinectskeleton.cs in which I created two DataTables and a boolean variables. The first DataTable is filled in the OnRender function while the other is empty. The boolean variable is set by default to false. So, what I want is when the button in the kinectwindow.xaml.cs is pressed the latest data in the filled DataTable is copied to the empty one. Then, when the checkbox is checked, the boolean value is set to true. So, how to do this?
I defined a function in the class kinectskeleton.cs that copies the data from the filled to the empty DataTable. In the OnClick function of the button of kinectwindow.xaml.cs, I created an object from class kinectskeleton and called this function but both DataTables are empty. Same for the checkbox in the CheckBox_Checked function: I set the boolean value of the class kinectskelton to true (and in the unchecked function I set it to false). But, the result is that in the kinectskelton class it's always set to the default value (false) and never enters the if condition I made for it to enter when it's true.
Hope it's now more clear and waiting for any suggestions. To download the toolkit, here is the link: http://www.microsoft.com/en-us/kinectforwindows/develop/developer-downloads.aspx
part of my code:
//------------------------------------------------------------------------------
// <copyright file="KinectWindow.xaml.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.Samples.Kinect.KinectExplorer
{
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.Kinect;
using Microsoft.Samples.Kinect.WpfViewers;
/// <summary>
/// Interaction logic for KinectWindow.xaml.
/// </summary>
public partial class KinectWindow : Window
{
public static readonly DependencyProperty KinectSensorProperty =
DependencyProperty.Register(
"KinectSensor",
typeof(KinectSensor),
typeof(KinectWindow),
new PropertyMetadata(null));
private readonly KinectWindowViewModel viewModel;
/// <summary>
/// Initializes a new instance of the KinectWindow class, which provides access to many KinectSensor settings
/// and output visualization.
/// </summary>
public KinectWindow()
{
this.viewModel = new KinectWindowViewModel();
// The KinectSensorManager class is a wrapper for a KinectSensor that adds
// state logic and property change/binding/etc support, and is the data model
// for KinectDiagnosticViewer.
this.viewModel.KinectSensorManager = new KinectSensorManager();
Binding sensorBinding = new Binding("KinectSensor");
sensorBinding.Source = this;
BindingOperations.SetBinding(this.viewModel.KinectSensorManager, KinectSensorManager.KinectSensorProperty, sensorBinding);
// Attempt to turn on Skeleton Tracking for each Kinect Sensor
this.viewModel.KinectSensorManager.SkeletonStreamEnabled = true;
this.DataContext = this.viewModel;
InitializeComponent();
}
public KinectSensor KinectSensor
{
get { return (KinectSensor)GetValue(KinectSensorProperty); }
set { SetValue(KinectSensorProperty, value); }
}
public void StatusChanged(KinectStatus status)
{
this.viewModel.KinectSensorManager.KinectSensorStatus = status;
}
private void Swap_Executed(object sender, ExecutedRoutedEventArgs e)
{
Grid colorFrom = null;
Grid depthFrom = null;
if (this.MainViewerHost.Children.Contains(this.ColorVis))
{
colorFrom = this.MainViewerHost;
depthFrom = this.SideViewerHost;
}
else
{
colorFrom = this.SideViewerHost;
depthFrom = this.MainViewerHost;
}
colorFrom.Children.Remove(this.ColorVis);
depthFrom.Children.Remove(this.DepthVis);
colorFrom.Children.Insert(0, this.DepthVis);
depthFrom.Children.Insert(0, this.ColorVis);
}
public KinectSkeleton ks = new KinectSkeleton();
private void Calibrate_Click(object sender, RoutedEventArgs e)
{
ks.setcurrentdt();
}
private void AngleDifference_Checked(object sender, RoutedEventArgs e)
{
ks.is_checked = true;
}
private void AngleDifference_Unchecked(object sender, RoutedEventArgs e)
{
ks.is_checked = false;
}
}
}
/// <summary>
/// A ViewModel for a KinectWindow.
/// </summary>
public class KinectWindowViewModel : DependencyObject
{
public static readonly DependencyProperty KinectSensorManagerProperty =
DependencyProperty.Register(
"KinectSensorManager",
typeof(KinectSensorManager),
typeof(KinectWindowViewModel),
new PropertyMetadata(null));
public KinectSensorManager KinectSensorManager
{
get { return (KinectSensorManager)GetValue(KinectSensorManagerProperty); }
set { SetValue(KinectSensorManagerProperty, value); }
}
}
}
namespace Microsoft.Samples.Kinect.WpfViewers
{
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Kinect;
using System.Data;
using System.Windows.Media.Media3D;
using System.Globalization;
/// <summary>
/// This control is used to render a player's skeleton.
/// If the ClipToBounds is set to "false", it will be allowed to overdraw
/// it's bounds.
/// </summary>
public class KinectSkeleton : Control
{
public bool is_checked=false;
public DataTable x = new DataTable();
public DataTable y = new DataTable();
protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
var currentSkeleton = this.Skeleton;
// Don't render if we don't have a skeleton, or it isn't tracked
if (drawingContext == null || currentSkeleton == null || currentSkeleton.TrackingState == SkeletonTrackingState.NotTracked)
{
return;
}
// Displays a gradient near the edge of the display where the skeleton is leaving the screen
this.RenderClippedEdges(drawingContext);
switch (currentSkeleton.TrackingState)
{
case SkeletonTrackingState.PositionOnly:
if (this.ShowCenter)
{
drawingContext.DrawEllipse(
this.centerPointBrush,
null,
this.Center,
BodyCenterThickness * this.ScaleFactor,
BodyCenterThickness * this.ScaleFactor);
}
break;
case SkeletonTrackingState.Tracked:
// here i defined the DataTables
if (is_checked == false)
{
//fill data table x with value a
}
else
{
//fill data table x with value b
}
break;
}
}
public void setcurrentdt()
{
//fill empty datatable "y" with filled one "x"
y = x.Copy();
}
}
}
xaml code of the checkbox:
<Window x:Class="Microsoft.Samples.Kinect.KinectExplorer.KinectWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Microsoft.Samples.Kinect.KinectExplorer"
xmlns:kt="clr-namespace:Microsoft.Samples.Kinect.WpfViewers;assembly=Microsoft.Samples.Kinect.WpfViewers"
Title="Kinect Explorer" Width="839" Height="768">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Microsoft.Samples.Kinect.WpfViewers;component/KinectControlResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
<local:KinectWindowsViewerSwapCommand x:Key="SwapCommand"/>
</ResourceDictionary>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource SwapCommand}" Executed="Swap_Executed"/>
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="Back" Command="{StaticResource SwapCommand}"/>
</Window.InputBindings>
<Grid Name="layoutGrid" Margin="10 0 10 0" TextBlock.FontFamily="{StaticResource KinectFont}">
<Grid.RowDefinitions>
<!-- The title bar -->
<RowDefinition Height="Auto"/>
<!-- The main viewer -->
<RowDefinition Height="*" MinHeight="300"/>
<!-- The audio panel -->
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<!-- The main viewer -->
<ColumnDefinition Width="*" MinWidth="400"/>
<!-- The side panels -->
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<DockPanel Grid.Row="0" Grid.ColumnSpan="2" Margin="10 0 10 20">
<Image DockPanel.Dock="Left" Source="Images\Logo.png" Stretch="None" HorizontalAlignment="Left" Margin="0 10 0 0"/>
<TextBlock DockPanel.Dock="Right"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Foreground="{StaticResource TitleForegroundBrush}" FontSize="{StaticResource LabelFontSize}">Kinect Explorer</TextBlock>
<Image Source="Images\Status.png" Stretch="None" HorizontalAlignment="Center"/>
</DockPanel>
<!-- The main viewer -->
<Grid Grid.Column="0" Grid.Row="1" Margin="10" >
<Grid Name="MainViewerHost">
<Grid Name="ColorVis" Background="{StaticResource DarkNeutralBrush}">
<Viewbox HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="Uniform">
<!-- Make the colorViewer and skeletonViewer overlap entirely. -->
<Grid>
<kt:KinectColorViewer x:Name="ColorViewer" KinectSensorManager="{Binding KinectSensorManager}" CollectFrameRate="True" RetainImageOnSensorChange="True" />
<Canvas>
<kt:KinectSkeletonViewer
KinectSensorManager="{Binding KinectSensorManager}"
Visibility="{Binding KinectSensorManager.ColorStreamEnabled, Converter={StaticResource BoolToVisibilityConverter}}"
Width="{Binding ElementName=ColorViewer,Path=ActualWidth}"
Height="{Binding ElementName=ColorViewer,Path=ActualHeight}"
ImageType="Color" />
</Canvas>
</Grid>
</Viewbox>
<Border
TextBlock.Foreground="{StaticResource LabelForegroundBrush}"
HorizontalAlignment="Right" VerticalAlignment="Top"
Background="{StaticResource MediumNeutralBrush}"
Width="50" Height="50">
<StackPanel Orientation="Vertical" >
<TextBlock FontSize="{StaticResource HeaderFontSize}" Text="{Binding ElementName=ColorViewer, Path=FrameRate}" HorizontalAlignment="Center" Margin="-2"/>
<TextBlock FontSize="{StaticResource FPSFontSize}" HorizontalAlignment="Center" Margin="-2">FPS</TextBlock>
</StackPanel>
</Border>
<Rectangle Fill="#7777" Visibility="{Binding KinectSensorManager.ColorStreamEnabled, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=True}"/>
</Grid>
</Grid>
</Grid>
<!-- The Audio panel -->
<Grid Grid.Row="2" Grid.Column="0"
Margin="10 10 10 20"
VerticalAlignment="Top">
<kt:KinectAudioViewer
x:Name="kinectAudioViewer"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
KinectSensorManager="{Binding KinectSensorManager}"/>
</Grid>
<!-- The side panels-->
<StackPanel
Orientation="Vertical"
Grid.Column="1"
Grid.Row="1"
Grid.RowSpan="2"
Margin="10"
HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid Name="SideViewerHost" Width="200" Height="150">
<Grid Name="DepthVis" Background="{StaticResource DarkNeutralBrush}">
<Viewbox Stretch="Uniform" HorizontalAlignment="Center" VerticalAlignment="Center">
<!-- Make the depthViewer and skeletonViewer overlap entirely. -->
<Grid>
<kt:KinectDepthViewer
x:Name="DepthViewer"
KinectSensorManager="{Binding KinectSensorManager}"
CollectFrameRate="True"
RetainImageOnSensorChange="True"/>
<Canvas>
<kt:KinectSkeletonViewer
KinectSensorManager="{Binding KinectSensorManager}"
Visibility="{Binding KinectSensorManager.DepthStreamEnabled, Converter={StaticResource BoolToVisibilityConverter}}"
Width="{Binding ElementName=DepthViewer, Path=ActualWidth}"
Height="{Binding ElementName=DepthViewer, Path=ActualHeight}"
ShowBones="true" ShowJoints="true" ShowCenter="true" ImageType="Depth" />
</Canvas>
</Grid>
</Viewbox>
<Border
TextBlock.Foreground="{StaticResource LabelForegroundBrush}"
HorizontalAlignment="Right" VerticalAlignment="Top"
Background="{StaticResource MediumNeutralBrush}"
Width="50" Height="50">
<StackPanel Orientation="Vertical" >
<TextBlock FontSize="{StaticResource HeaderFontSize}" Text="{Binding ElementName=DepthViewer, Path=FrameRate}" HorizontalAlignment="Center" Margin="-2"/>
<TextBlock FontSize="{StaticResource FPSFontSize}" HorizontalAlignment="Center" Margin="-2">FPS</TextBlock>
</StackPanel>
</Border>
<Rectangle Fill="#7777" Visibility="{Binding KinectSensorManager.DepthStreamEnabled, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=True}"/>
</Grid>
<Button HorizontalAlignment="Left" VerticalAlignment="Top" Command="{StaticResource SwapCommand}">
<Button.Template>
<ControlTemplate>
<Border Width="50" Height="50">
<Border.Style>
<Style>
<Style.Setters>
<Setter Property="Border.Background" Value="{StaticResource MediumNeutralBrush}"/>
</Style.Setters>
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.TemplatedParent}, Path=IsMouseOver}" Value="True">
<Setter Property="Border.Background" Value="{StaticResource DarkNeutralBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<Image Source="Images/swap.png"/>
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</Grid>
<kt:KinectSettings KinectSensorManager="{Binding KinectSensorManager}" Margin="0 20 0 0" />
</StackPanel>
<Button Content="Calibrate" Height="23" x:Name="Calibrate" x:FieldModifier="public" Width="75" Margin="213,45,289,435" Grid.RowSpan="2" Click="Calibrate_Click" />
<CheckBox Content="AngleDifference" Height="25" x:Name="AngleDifference" x:FieldModifier="public" Width="135" Margin="0,45,137,433" Grid.RowSpan="2" Checked="AngleDifference_Checked" HorizontalAlignment="Right" Unchecked="AngleDifference_Unchecked" />
</Grid>
</Window>
ViewModel class:
public class ViewModel
{
public bool IsChecked { get; set; }
public bool is_clicked { get; set; }
}
Without seeing the complete KinectWindow.xaml file or downloading the SDK I'm taking a bit of a guess, but it seems to me that your problems are caused by having two different instances of KinectSkeleton:
ks that you're instantiating in KinectWindow, setting its is_checked property and calling setcurrentdt
the one declared somewhere in KinectWindow.xaml in which OnRender is being called.
How to fix this problem?
Find KinectSkeleton in KinectWindow.xaml. It should be defined like this (instead of local, a different namespace prefix could be used):
<local:KinectSkeleton ... />
Give it a name so that you can reference it from code behind in KinextWindow.xaml.cs by adding the x:Name attribute. If you name it ks you won't need to change your existing code modifications:
<local:KinectSkeleton x:Name="ks" ... />
Delete your declaration of KinectSkeleton class in code behind to prevent the clash:
public KinectSkeleton ks = new KinectSkeleton();
Now you will have only a single instance of KinectSkeleton, therefore OnRender will work with the same data that you're modifying from your event handlers.

Categories

Resources