WPF- TimePicker is not updating - c#

I'm using Time Picker from wpfToolkit.extended in WPF application.
When I select a time in the dropdrownlist everything works the way it should. This is the namespace of the toolkit.
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
This is the xaml for the timepicker
<Controls:MetroWindow
x:Class="TimeSheet.DayView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:e="http://schemas.microsoft.com/developer/msbuild/2003"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:TimeSheet.Views.DataTemplateSpace"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
x:Name="MainWin"
Title="DayView" Width="596" Height="596">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- <Style x:Key="ColoringStyle" TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
<Style.Triggers>
<DataTrigger Binding="{Binding isSynced}" Value="true">
<Setter Property="Background" Value="Gold"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding isSynced}" Value="false">
<Setter Property="Background" Value="Aqua"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>-->
<!-- Default DataTemplate -->
<DataTemplate x:Key="DefaultDataTemplate" >
<StackPanel Orientation="Horizontal" Width="596">
<TextBlock Text="{Binding ClientNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="145"/>
<TextBlock Text="{Binding ApplicationNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="90"/>
<TextBlock Text="{Binding StartTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="100"/>
<TextBlock Text="{Binding StopTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="60"/>
<TextBlock Text="{Binding TaskNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="71"/>
<TextBlock Text="{Binding ProjectNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="130"/>
</StackPanel>
</DataTemplate>
<!-- Editable DataTemplate -->
<DataTemplate x:Key="EditableDataTemplate">
<StackPanel Orientation="Horizontal" Width="596">
<!--<ComboBox x:Name="ClientComboBox" SelectionChanged="ClientComboBoxChanged" ItemsSource="{Binding Path=clientList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ClientNameBindingClass, Mode=OneWayToSource}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="145"/>-->
<TextBox Text="{Binding ClientNameBinding,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="145"/>
<TextBox Text="{Binding ApplicationNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="90"/>
<xctk:TimePicker Name="StartPicker" TextBoxBase.TextChanged="StartPicker_TextChanged" Value="{Binding StartValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/>
<xctk:TimePicker Name="EndPicker" TextBoxBase.TextChanged="EndPicker_TextChanged" Value="{Binding EndValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" EndTime="11:59:0"/>
<TextBox Text="{Binding TaskNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="71"/>
<ComboBox x:Name="ProjectComboBox" ItemsSource="{Binding Path=projectList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ProjectNameBindingClass, Mode=OneWayToSource}" Width="130" Background="Yellow" BorderThickness="0"/>
</StackPanel>
</DataTemplate>
<!-- DataTemplate Selector -->
<l:DayViewListDataTemplateSelector x:Key="templateSelector"
DefaultDataTemplate="{StaticResource DefaultDataTemplate}"
EditableDataTemplate="{StaticResource EditableDataTemplate}"/>
</ResourceDictionary>
</Window.Resources>
<Viewbox Stretch="Fill" Width="{Binding Width, ElementName=MainWin}" Height="{Binding Height, ElementName=MainWin}">
<Grid Margin="0,0,0,-4" Background="#FF3399FF" Height="557">
<Button x:Name="BackButton" Style="{DynamicResource MetroCircleButtonStyle}" Content="<---" Foreground="Blue" Click="BackButton_Click" Margin="7,2,524,491"/>
<Button x:Name="TimerButton" Width="124" Height="46" Click="TimerButton_Click" Margin="172,12,300,499">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
<GradientStop Color="#FF5B6CB8"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Label x:Name="monthLabel" Content="May" RenderTransformOrigin="2.34,0.545" FontFamily="Times New Roman" FontSize="20" Margin="431,2,90,522"/>
<Label x:Name="dayDateLabel" Content="Friday, 27" RenderTransformOrigin="0.446,0.226" FontFamily="Times New Roman" FontSize="36" FontWeight="Bold" Margin="376,35,38,467"/>
<StackPanel Orientation="Horizontal" Margin="-1,93,1,434" RenderTransformOrigin="1.155,0.47" Height="25">
<TextBox Text="Client" HorizontalContentAlignment="Center" Width="145" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="Application" HorizontalContentAlignment="Center" Width="90" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="StartTime" HorizontalContentAlignment="Center" Canvas.Left="148" Canvas.Top="86" Width="100" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" RenderTransformOrigin="0.5,0.5" VerticalContentAlignment="Center"/>
<TextBox Text="StopTime" HorizontalContentAlignment="Center" Width="60" RenderTransformOrigin="0.471,0.692" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="Task" HorizontalContentAlignment="Center" Canvas.Left="378" Canvas.Top="86" Width="130" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="Project" HorizontalContentAlignment="Center" Width="71" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
</StackPanel>
<ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,131,0,59" ItemTemplateSelector="{StaticResource templateSelector}" SelectionMode="Single">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseDoubleClick" Handler="listBox1_MouseDoubleClick">
</EventSetter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<Button x:Name="SyncEntry" Content="Sync All" HorizontalAlignment="Left" Margin="476,498,0,0" VerticalAlignment="Top" Width="95" Click="SyncEntry_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
<GradientStop Color="#FF5256AC"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Button x:Name="EditButton" Content="Edit" HorizontalAlignment="Left" Margin="393,498,0,0" VerticalAlignment="Top" Width="75" Click="EditButton_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
<GradientStop Color="#FF5256AC"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Button x:Name="CustomButton" Content="Add" HorizontalAlignment="Left" Margin="0,70,0,0" VerticalAlignment="Top" Width="75" FontSize="12" Height="20" FontWeight="Normal" Click="CustomButton_Click"/>
</Grid>
</Viewbox>
I've seen solution for this here
but when I write C# code-
public partial class DayView : MetroWindow, INotifyPropertyChanged
{
private DateTime currentDateForWindow;
public List<Harvest_Project> projectList{get;set;}
public List<Harvest_Client> clientList {get; set;}
public Harvest_Project selectedProjectid {get; set;}
public Harvest_Client selectedClientid {get; set;}
public string ElementName { get; set; }
public DateTime StartValue { get; set; }
public DateTime EndValue { get; set; }
public DayView(DateTime s)
{
InitializeComponent();
this.DataContext = this;
Globals._globalController.setDayViewWindow(this);
currentDateForWindow = s;
dayDateLabel.Content = s.DayOfWeek + ", " + s.Day;
monthLabel.Content = s.ToString("MMMM");
if(Globals._globalController.win32Manager.isTimerRunning)
TimerButton.Content = "Stop";
else
TimerButton.Content = "Start";
listBox1.Items.Clear();
listBox1.MouseDoubleClick += new MouseButtonEventHandler(listBox1_MouseDoubleClick);
clientList = Globals._globalController.harvestManager._CLIENTLIST;
projectList = Globals._globalController.harvestManager._PROJECTLIST;
Globals._globalController.fetchAndPopulateForDate(currentDateForWindow);
Globals.ni2 = new NotifyIcon();
Globals.ni2.Icon = TimeSheet.Properties.Resources.DayViewIcon;
Globals.ni2.Visible = true;
Globals.ni2.Click +=
delegate(object sender, EventArgs args)
{
this.Show();
this.WindowState = WindowState.Normal;
};
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == System.Windows.WindowState.Minimized)
{
this.Hide();
Globals.ni2.BalloonTipTitle = "DayView";
Globals.ni2.BalloonTipText = "This is Day window";
Globals.ni2.Visible = true;
Globals.ni2.ShowBalloonTip(500);
base.OnStateChanged(e);
}
}
public void addHarvestEntrytoView(Harvest_TimeSheetEntry entry)
{
listBox1.Items.Add(entry);
}
public void addHarvestEntrytoView(List<Harvest_TimeSheetEntry> entry)
{
foreach (Harvest_TimeSheetEntry x in entry)
listBox1.Items.Add(x);
}
private void BackButton_Click(object sender, RoutedEventArgs e)
{
Globals.ni2.Visible=false;
this.Hide();
Globals._globalController.getMonthViewWindow.Show();
Globals.ni1.Visible = true;
}
private void TimerButton_Click(object sender, RoutedEventArgs e)
{
if (!Globals._globalController.win32Manager.isTimerRunning)
{
Globals._globalController.win32Manager.startTimer();
this.TimerButton.Content = "Stop";
}
else
{
Globals._globalController.win32Manager.stopTimer();
this.TimerButton.Content = "Start";
}
}
private void SyncEntry_Click(object sender, RoutedEventArgs e)
{
//Submit All unsynced Entries
foreach(Harvest_TimeSheetEntry item in listBox1.Items)
{
if (!item.isSynced)
{
if (item.ProjectNameBinding == "Select Project" && item.ClientNameBinding == "Select Client")
System.Windows.MessageBox.Show("Please select you Project and Client");
else
//Check if something is selected in selectedProjectItem For that item
Globals._globalController.harvestManager.postHarvestEntry(item);
System.Windows.MessageBox.Show("Entry posted");
}
}
}
private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
//Submit clicked Entry
if (sender is ListBoxItem)
{
ListBoxItem item = (ListBoxItem)sender;
Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)item.DataContext;
if (!entryToPost.isSynced)
{
//Check if something is selected in selectedClientItem and selectedProjectItem For that items
if (entryToPost.ClientNameBinding == "Select Client" || entryToPost.ProjectNameBinding == "Select Project")
System.Windows.MessageBox.Show("Please select you Project and Client");
else
{
Globals._globalController.harvestManager.postHarvestEntry(entryToPost);
System.Windows.MessageBox.Show("Entry posted");
DataTemplate tmpl = (DataTemplate)this.FindResource("DefaultDataTemplate");
listBox1.ItemTemplate = tmpl;
}
}
else
{
//Already synced.. Make a noise or something
System.Windows.MessageBox.Show("Already Synced;TODO Play a Sound Instead");
}
}
}
private void EditButton_Click(object sender, RoutedEventArgs e)
{
foreach (Harvest_TimeSheetEntry item in listBox1.Items)
{
if (item.isSynced)
{
item.isSynced = false;
listBox1.ItemTemplate = (DataTemplate)this.FindResource("EditableDataTemplate");
this.EditButton.Content = "Done Editing";
}
else
{
listBox1.ItemTemplate = (DataTemplate)this.FindResource("DefaultDataTemplate");
this.EditButton.Content = "Edit";
Globals._globalController.harvestManager.postHarvestEntry(item);
System.Windows.MessageBox.Show("Entry posted");
}
}
}
private void CustomButton_Click(object sender, RoutedEventArgs e)
{
Globals.ni2.Visible=false;
CustomView c = new CustomView(Globals._globalController.getDayViewWindow);
c.Show();
this.Hide();
Globals.ni3.Visible = true;
}
private void StartPicker_TextChanged(object sender, TextChangedEventArgs e)
{
StartPicker.Focus();
}
private void EndPicker_TextChanged(object sender, TextChangedEventArgs e)
{
EndPicker.Focus();
}
protected virtual void OnPropertyChanged(String time)
{
if (System.String.IsNullOrEmpty(time))
{
return;
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(time));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
It shows error as "StartPicker and EndPicker does not exist in current context".
Suggest the ways to solve this error.

Xaml-
<Grid>
<xctk:TimePicker Name="StartPicker" TextBoxBase.TextChanged="StartPicker_TextChanged" Value="{Binding StartTimeBinding, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" Height="50" EndTime="11:59:0"/>
<xctk:TimePicker Name="EndPicker" TextBoxBase.TextChanged="EndPicker_TextChanged" Value="{Binding StopTimeBinding, ElementName=MainWin1, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" Height="50" EndTime="11:59:0"/>
</Grid>
Code-Behind your Xaml in Xaml.cs
private void EndPicker_TextChanged(object sender, TextChangedEventArgs e)
{
StartPicker.Focus(); // shows error at TimePicker Name(i.e StartPicker)
}
private void StartPicker_TextChanged(object sender, TextChangedEventArgs e)
{
EndPicker.Focus(); // shows error at EndPicker
}

Try it this way:
private void StartPicker_TextChanged(object sender, TextChangedEventArgs e)
{
TimePicker tp = sender as TimePicker;
if(tp != null)
{
tp.Focus();
}
}
private void EndPicker_TextChanged(object sender, TextChangedEventArgs e)
{
TimePicker tp = sender as TimePicker;
if(tp != null)
{
tp.Focus();
}
}
Of course you can have only one function and point from both timepickers to this function:
private void TimePicker_TextChanged(object sender, TextChangedEventArgs e)
{
TimePicker tp = sender as TimePicker;
if(tp != null)
{
tp.Focus();
}
}
and then in the xaml:
<xctk:TimePicker Name="StartPicker" TextBoxBase.TextChanged="TimePicker_TextChanged" Value="{Binding StartValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/>
<xctk:TimePicker Name="EndPicker" TextBoxBase.TextChanged="TimePicker_TextChanged" Value="{Binding EndValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" EndTime="11:59:0"/>

Related

ListBox WPF Multiselect Not working

I am trying to select multiple options from a listbox. I even tried using Multiple Selection mode but it doesnot work for this specific listbox but works for others. ListBox name is listBox. I am adding the data to that list dynamically in OrderWindow class and i have implemented the selection_changed method but i am unable to select multiple items and i have also binded a list to this listbox.
Here is the code:
namespace ACW2
{
/// <summary>
/// Interaction logic for OrderWindow.xaml
/// </summary>
public partial class OrderWindow : Window
{
List<MenuClass> PizzaInStock = new List<MenuClass>();
List<InvClass> inventory = MainWindow.ItemList;
List<InvClass> pizzatoppings = new List<InvClass>();
List<String> Mainlist = new List<String>();
String addpizzas = "";
double pizzaprice = 0;
private void extratoppingslist(String name)
{
pizzatoppings = new List<InvClass>();
var pizza = MainWindow.MenuList.FirstOrDefault(x => x.Name == name);
List<Ingredient> originaltoppings = pizza.Ingredients;
int originaltoppingsize = pizza.Ingredients.Count;
if (originaltoppingsize >= 5)
{
return;
}
var allpizzatoppings = from a in inventory
where a.Category == "pizza"
select a;
foreach (InvClass item in allpizzatoppings)
{
int exists = 0;
if (originaltoppingsize == 5)
{
break;
}
foreach(Ingredient ing in originaltoppings)
{
if (item.Name.Equals(ing.Name))
{
exists = 1;
break;
}
}
if (exists == 0)
{
pizzatoppings.Add(item);
}
++originaltoppingsize;
}
listBox.ItemsSource = null;
listBox.ItemsSource = pizzatoppings;
}
private void updatepizzaprice()
{
pizzaprice = 0;
if (comboBox1.SelectedItem != null&& comboBox.SelectedItem != null)
{
String pizza = comboBox.SelectedItem.ToString();
String size = comboBox1.SelectedItem.ToString();
extratoppingslist(pizza);
var iteminlists = MainWindow.MenuList.FirstOrDefault(x => (x.Name == pizza) && (x.Size == size));
pizzaprice += (Convert.ToDouble(iteminlists.Price));
List<Ingredient> list = iteminlists.Ingredients;
if (checkBox.IsChecked == true)
{
foreach(Ingredient iss in list)
{
Trace.WriteLine(iss.Name);
}
var item = list.FirstOrDefault(x => x.Name == " dough");
var ingr= inventory.FirstOrDefault(x => x.Name == " dough");
pizzaprice += ((Convert.ToDouble(item.Quantity) * 0.1))*ingr.Price;
var items = list.FirstOrDefault(x => x.Name == " mozzarella");
var ingrs = inventory.FirstOrDefault(x => x.Name == " mozzarella");
pizzaprice += ((Convert.ToDouble(items.Quantity) * 0.15)) * ingrs.Price;
}
List<InvClass> toppings = listBox.SelectedItems.Cast<InvClass>().ToList();
foreach (InvClass top in toppings)
{
var item = inventory.FirstOrDefault(x => x.Name == top.Name);
Trace.WriteLine(top.Name);
if (iteminlists.Size == " regular")
{
pizzaprice += item.Price * 0.25;
}
else if (iteminlists.Size == " large")
{
pizzaprice += item.Price * 0.35;
}
else if (iteminlists.Size == " extra-large")
{
pizzaprice += item.Price * 0.75;
}
}
textBox.Text = "£ " + pizzaprice.ToString();
}
}
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void checkBox_Checked(object sender, RoutedEventArgs e)
{
updatepizzaprice();
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
updatepizzaprice();
}
private void checkBox_unchecked(object sender, RoutedEventArgs e)
{
updatepizzaprice();
}
private void checkbox1_unchecked(object sender, RoutedEventArgs e)
{
updateburgerprice();
}
private void checkbox2_unchecked(object sender, RoutedEventArgs e)
{
updateburgerprice();
}
}
}
Here is the xml code:
<Window x:Class="ACW2.OrderWindow"
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:ACW2"
mc:Ignorable="d"
Title="OrderWindow" SizeToContent="WidthAndHeight">
<StackPanel Orientation="Vertical">
<Label x:Name="label10" Content="Create Order" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" FontSize="24"/>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top">
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label4_Copy" Content="Order Summary" Margin="5" FontSize="16"/>
<ListBox x:Name="listBox2" Height="160" Margin="5" MinWidth="180"/>
<Button x:Name="button4" Content="Remove Item" Margin="5" Width="75"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label13" Content="Ingredient Cost (£)" Margin="5" VerticalAlignment="Top"/>
<TextBox x:Name="textBox4" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label12" Content="Net Profit (£)" Margin="5"/>
<TextBox x:Name="textBox5" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label11" Content="Total Price(£)" Margin="5"/>
<TextBox x:Name="textBox1" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button3" Content="Complete Order" Margin="5"/>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label4" Content="1. Pizzas" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label1" Content="Pizza" Margin="5" />
<ComboBox x:Name="comboBox" Margin="5" Width="120" SelectionChanged="comboBox_SelectionChanged"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label" Content="Size" Margin="5"/>
<ComboBox x:Name="comboBox1" Margin="5" Width="120" SelectionChanged="comboBox1_SelectionChanged"/>
</StackPanel>
<CheckBox x:Name="checkBox" Content="Stuffed Crust" Margin="5" HorizontalAlignment="Center" Checked="checkBox_Checked" Unchecked="checkBox_unchecked"/>
<Label x:Name="label14" Content="Extra Toppings" Margin="5,5,5,0" HorizontalAlignment="Center"/>
<ListBox x:Name="listBox" Height="120" Margin="5,0,5,5" MinWidth="140" HorizontalAlignment="Center" SelectionChanged="listBox_SelectionChanged" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate x:Name="Lists">
<TextBlock>
<Run Text="{Binding Name}"/>
<Run Text=" , "/>
<Run Text="{Binding Price}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label9" Content="Price (£)" Margin="5"/>
<TextBox x:Name="textBox" Height="24" Margin="5" TextWrapping="Wrap" Text="£" VerticalAlignment="Top" Width="80"/>
</StackPanel>
<Button x:Name="button" Content="Add to Order" Margin="5" Width="80" HorizontalAlignment="Right"/>
</StackPanel>
</Border>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label5" Content="2. Burgers" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label2" Content="Burger" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top"/>
<ComboBox x:Name="comboBox2" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Top" Width="107" SelectionChanged="comboBox2_SelectionChanged"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label3" Content="Size" Margin="5" VerticalAlignment="Center"/>
<RadioButton x:Name="radioButton" Content="1/4lb" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" Checked="radioButton_Checked"/>
<RadioButton x:Name="radioButton1" Content="1/2lb" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" Checked="radioButton1_Checked"/>
</StackPanel>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center">
<CheckBox x:Name="checkBox1" Content="Salad" Margin="2" Checked="checkBox1_Checked" Unchecked="checkbox1_unchecked"/>
<CheckBox x:Name="checkBox2" Content="Cheese" Margin="2" Checked="checkBox2_Checked" Unchecked="checkbox2_unchecked"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Label x:Name="label8" Content="Price (£)" HorizontalAlignment="Left" Margin="5" />
<TextBox x:Name="textBox2" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button1" Content="Add to Order" Margin="5" Width="80" HorizontalAlignment="Right" Click="button1_Click"/>
</StackPanel>
</Border>
</StackPanel>
<StackPanel Orientation="Vertical" VerticalAlignment="Top">
<Label x:Name="label6" Content="3. Sundries" Margin="5" FontSize="16"/>
<Border BorderBrush="Gray" BorderThickness="1" Margin="5">
<StackPanel Orientation="Vertical">
<ListBox x:Name="listBox1" Height="120" MinWidth="140" Margin="5" SelectionChanged="listBox1_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate x:Name="Lists11">
<TextBlock Background="{Binding Color}">
<Run Text="{Binding Name}"/>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel Orientation="Horizontal">
<Label x:Name="label7" Content="Price (£)" Margin="5" VerticalAlignment="Top"/>
<TextBox x:Name="textBox3" Height="24" Margin="5" TextWrapping="Wrap" Text="£" Width="80"/>
</StackPanel>
<Button x:Name="button2" Content="Add to Order" HorizontalAlignment="Right" Margin="5" Width="80" Click="button2_Click"/>
</StackPanel>
</Border>
</StackPanel>
</StackPanel>
</StackPanel>
</Window>

WPF - Change Controls based on listviewitem selection. Controls not updating

I'm trying to update the controls present on my Main Window based on the listviewitem selected by the user, but when the listviewitem selection is changed the controls do not update.
I used this post as reference How to dynamically change a WPF control's template using a checkbox?
EDIT: I initially used ContentTemplate but changed this to DataTemplate based on suggestions, however it still is not updating
The XMAL for my Main Window is
<Window.Resources>
<DataTemplate x:Key="Default">
<Grid Margin="20,280,0,0" />
</DataTemplate>
<DataTemplate x:Key="ERAFileSelect">
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="218" Margin="20,280,0,0" VerticalAlignment="Top" Width="257" CornerRadius="15">
<Grid Name="grdFileSelect">
<Label x:Name="lblProcessContent" Content="Drag File or Manually Select File" HorizontalAlignment="Center" VerticalAlignment="Top" Width="257" HorizontalContentAlignment="Center"/>
<TextBox x:Name="txtEraFileName" HorizontalAlignment="Left" Height="23" Margin="10,80,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="235"/>
<Button x:Name="btnSelectFiles" Content="Manually Select File(s)" HorizontalAlignment="Left" Margin="10,161,0,0" VerticalAlignment="Top" Width="235" Height="45"/>
</Grid>
</Border>
</DataTemplate>
<DataTemplate x:Key="FCSFileSelect">
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="218" Margin="20,280,0,0" VerticalAlignment="Top" Width="257" CornerRadius="15">
<Grid Name="grdFileSelect">
<Label x:Name="lblProcessContent" Content="Drag File or Manually Select Files" HorizontalAlignment="Center" VerticalAlignment="Top" Width="257" HorizontalContentAlignment="Center"/>
<TextBox x:Name="txtFCSFileName_TQ02" HorizontalAlignment="Left" Height="23" Margin="10,40,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="174"/>
<Button x:Name="btnSelectFiles_TQ02" Content="Select" HorizontalAlignment="Left" Margin="189,37,0,0" VerticalAlignment="Top" Width="56" Height="28"/>
<TextBox x:Name="txtFCSFileName_TQ11" HorizontalAlignment="Left" Height="23" Margin="10,105,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="174"/>
<Button x:Name="btnSelectFiles_TQ11" Content="Selec" HorizontalAlignment="Left" Margin="189,100,0,0" VerticalAlignment="Top" Width="56" Height="28"/>
<TextBox x:Name="txtFCSFileName_TQ16" HorizontalAlignment="Left" Height="23" Margin="10,170,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="174"/>
<Button x:Name="btnSelectFiles_TQ16" Content="Select" HorizontalAlignment="Left" Margin="189,165,0,0" VerticalAlignment="Top" Width="56" Height="28"/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Grid Margin="0,0,2,0">
<GroupBox x:Name="gbxProgress" Header="Progress" HorizontalAlignment="Left" Margin="298,105,0,0" VerticalAlignment="Top" Height="445" Width="462" Foreground="Black">
<ListBox x:Name="lbxProgress" HorizontalAlignment="Left" Height="408" Margin="10,10,0,0" VerticalAlignment="Top" Width="431" Foreground="Black" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Progress.Message}" />
</GroupBox>
<Button x:Name="btnStart" Content="Start" HorizontalAlignment="Left" Margin="20,513,0,0" VerticalAlignment="Top" Width="100" Height="37" IsEnabled="{Binding Properties.StartButtonEnabled}" Click="btnStart_Click"/>
<Button x:Name="btnCancel" Content="Cancel" HorizontalAlignment="Left" Margin="177,513,0,0" VerticalAlignment="Top" Width="100" Height="37"/>
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="70" Margin="20,21,0,0" VerticalAlignment="Top" Width="740" CornerRadius="15">
<Grid>
<Image HorizontalAlignment ="Left" Margin="10" Height="50" Width="50" VerticalAlignment="Center" Source="/Lib/Icons/User.png" />
<TextBlock Name="txtUser" FontSize="20" Height="30" Width="200" Foreground="Red" HorizontalAlignment="Left" Margin="78,19,0,19"/>
<Image HorizontalAlignment ="Left" Margin="443,8,0,10" Height="50" Width="50" VerticalAlignment="Center" Source="Lib/Icons/Watch.png" />
<TextBlock x:Name="txtRunTime" FontSize="20" Height="30" Width="200" Foreground="Red" HorizontalAlignment="Left" Margin="519,19,0,19" Text="{Binding AppRunTime.TimeElapsed}" />
</Grid>
</Border>
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="144" Margin="20,119,0,0" VerticalAlignment="Top" Width="257" CornerRadius="15">
<Grid>
<Label x:Name="lblProcessSelection" Content="Process Selection" HorizontalAlignment="Center" VerticalAlignment="Top" Width="257" HorizontalContentAlignment="Center"/>
<ListView x:Name="lvProcessSelection" HorizontalAlignment="Left" Height="93" Margin="10,30,0,0" VerticalAlignment="Top" Width="235" BorderThickness="0" SelectionChanged="lvProcessSelection_SelectionChanged">
<ListViewItem Name="itmERA" Content="Expense Reserve Automation"/>
<ListViewItem Name="itmFCS" Content="Financial Close Status"/>
<ListViewItem Name="itmPEL" Content="Peel"/>
</ListView>
</Grid>
</Border>
<ContentControl DataContext="{Binding Properties}" Content="{Binding}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Setter Property="ContentTemplate" Value="{StaticResource ERAFileSelect}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedProcess}" Value="Expense Reserve Automation">
<Setter Property="ContentTemplate" Value="{StaticResource ERAFileSelect}" />
</DataTrigger>
<DataTrigger Binding="{Binding SelectedProcess}" Value="Financial Close Status">
<Setter Property="ContentTemplate" Value="{StaticResource FCSFileSelect}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</Grid>
ViewModel Code is
public class MainWindowModel
{
public ApplicationRunTime AppRunTime { get; set; }
public LogMessage Progress { get; set; }
public MainWindowProperties Properties { get; set; }
public MainWindowModel()
{
AppRunTime = new ApplicationRunTime();
Progress = new LogMessage();
Properties = new MainWindowProperties();
Properties.StartButtonEnabled = false;
}
}
With the MainWindowProperties class
public class MainWindowProperties
{
public bool StartButtonEnabled { get; set; }
public string SelectedProcess { get; set; }
}
And within my MainWindow Constructor I have set the DataContext
mainWindowModel = new MainWindowModel();
this.DataContext = mainWindowModel;
When the selection from lvProcessSelection is changed the following code is executed
if (lvProcessSelection.SelectedItems.Count > 0)
{
mainWindowModel.Properties.SelectedProcess = ((ListViewItem)lvProcessSelection.SelectedItem).Content.ToString();
}
else
{
mainWindowModel.Properties.SelectedProcess = string.Empty;
}
This will update SelectedProcess within my ViewModel with either "Expense Reserve Automation" or "Financial Close Status"
I know the DataContext is set correctly for my ViewModel (but may not be for the ContentControl) as I am able to update lbxProgress with new messages and update txtRunTime with the application RunTime
However when I change the selection on lvProcessSelection nothing happens; the default controls of ERAFileSelect remains.
Could anybody point me in the right direction on how to solve this?
Could anybody point me in the right direction on how to solve this?
Your MainWindowProperties class should implement the INotifyPropertyChanged interface and raise change notifications whenever the SelectedProcess property is set to a new value:
public class MainWindowProperties : INotifyPropertyChanged
{
public bool StartButtonEnabled { get; set; }
private string _selectedProcess;
public string SelectedProcess
{
get { return _selectedProcess; }
set { _selectedProcess = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Please refer to MSDN for more information about this common interface: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx
Every view model/model that you bind to must implement this interface and raise change notifications for any target value in the view to be updated.
Why you are not using Data template? Data template will work in this scenario.

Playing incoming audio stream on different pages

I am building some Shared Project which is connected with Playing incoming internet radio stream.
Currently I ve got a problem with Playing this stream on different pages.
I made some background task and it works fine I can easily minimize my app but when I am moving to different page where the user will read the RSS feed (Frame.Navigate some DataContext which contains the RSS),the Media Element stop playing.
I try to find some solution myself, but I didn't find any which will be the best for my.
Thank you for your help
public sealed partial class MainPage : Page
{
SystemMediaTransportControls systemControls = SystemMediaTransportControls.GetForCurrentView();
FeedDataSource feedDataSource = (FeedDataSource)App.Current.Resources["feedDataSource"];
FeedData nFeedData = new FeedData();
public MainPage()
{
this.InitializeComponent();
InitializeTransportControls();
}
private void Media_CurrentStateChanged(object sender, RoutedEventArgs e)
{
switch (Media.CurrentState)
{
case MediaElementState.Closed:
systemControls.PlaybackStatus = MediaPlaybackStatus.Closed;
break;
case MediaElementState.Paused:
systemControls.PlaybackStatus = MediaPlaybackStatus.Paused;
break;
case MediaElementState.Playing:
systemControls.PlaybackStatus = MediaPlaybackStatus.Playing;
break;
case MediaElementState.Stopped:
systemControls.PlaybackStatus = MediaPlaybackStatus.Stopped;
break;
default:
break;
}
}
private async void PlayButton_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Media.Play();
});
}
private async void StopButton_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Media.Stop();
});
}
private async void PauseButton_Click(object sender, RoutedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Media.Pause();
});
}
private void VolumeSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
Media.Volume = e.NewValue;
}
void InitializeTransportControls()
{
// Windows.Media
systemControls.ButtonPressed += systemControls_ButtonPressed;
systemControls.IsPlayEnabled = true;
systemControls.IsPauseEnabled = true;
}
// Handle ButtonPressed for systemControls
void systemControls_ButtonPressed(SystemMediaTransportControls sender, SystemMediaTransportControlsButtonPressedEventArgs args)
{
switch (args.Button)
{
case SystemMediaTransportControlsButton.Pause:
Media.Play();
break;
case SystemMediaTransportControlsButton.Play:
Media.Pause();
break;
default:
break;
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
if (feedDataSource != null)
{
if (feedDataSource.Feeds.Count == 0)
{
await feedDataSource.GetFeedsAsync();
}
MenuSection.DataContext = feedDataSource.Feeds;
}
}
private void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Contetnview_ItemClick(object sender, ItemClickEventArgs e)
{
}
private void Contetnview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var x
= ((GridView)sender).SelectedItem;
var z = ((Grid)x).Tag.ToString();
switch (z)
{
case "1":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[0]);
break;
case "2":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[3]);
break;
case "3":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[2]);
break;
case "4":
Frame.Navigate(typeof(ReadNewsPage), feedDataSource.Feeds[1]);
break;
}
}
}
<Grid x:Name="ThisGris" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<MediaElement x:Name="Media" Source="http://5.201.13.191:80/live" HorizontalAlignment="Left" Height="206" Margin="107,372,0,0" VerticalAlignment="Top" Width="213" AudioCategory="BackgroundCapableMedia" AutoPlay="False" CurrentStateChanged="Media_CurrentStateChanged"/>
<Hub x:Name="MainHubPage" Header="" Margin="0,3,0,-3" >
<Hub.Background>
<ImageBrush />
</Hub.Background>
<HubSection Header="Radio" Width="402" IsHeaderInteractive="True">
<DataTemplate>
<Grid Width="429" Height="565" d:IsLocked="True">
<Button x:Name="PlayButton" Content="Play" HorizontalAlignment="Left" Margin="118,352,0,0" VerticalAlignment="Top" Height="58" Width="83" Click="PlayButton_Click" d:IsLocked="True"/>
<Button x:Name="StopButton" Content="Stop" HorizontalAlignment="Left" Margin="7,352,0,0" VerticalAlignment="Top" Height="58" Click="StopButton_Click" d:IsLocked="True"/>
<Button x:Name="PauseButton" Content="Pause" HorizontalAlignment="Left" Margin="236,352,0,0" VerticalAlignment="Top" Height="58" Click="PauseButton_Click" d:IsLocked="True"/>
<Slider x:Name="VolumeSlider" HorizontalAlignment="Left" Margin="53,295,0,0" VerticalAlignment="Top" Width="267" Minimum="0" Value="50" Maximum="100" ValueChanged="VolumeSlider_ValueChanged" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="10,129,0,0" TextWrapping="Wrap" FontSize="20" Text="Na antenie :" VerticalAlignment="Top" Height="40" Width="135" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="10,174,0,0" TextWrapping="Wrap" FontSize="20" Text="Gramy :" VerticalAlignment="Top" Height="42" Width="135" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="10,216,0,0" FontSize="20" TextWrapping="Wrap" Text="Wkrótce : " VerticalAlignment="Top" Height="42" Width="118" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="150,216,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="42" Width="269" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Height="40" Margin="150,129,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="269" d:IsLocked="True"/>
<TextBlock HorizontalAlignment="Left" Margin="150,174,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="42" Width="293" d:IsLocked="True"/>
</Grid>
</DataTemplate>
</HubSection>
<HubSection x:Name="MenuSection" Width="606" IsHeaderInteractive="True">
<DataTemplate>
<GridView x:Name="Contetnview"
DataContext="{Binding}"
Height="519" Width="606" SelectionChanged="Contetnview_SelectionChanged" >
<Grid x:Name="Dowiadomosci" Height="135" Width="161" Tag="1" DataContext="{Binding }">
<TextBlock Text="Wiadomości"/>
</Grid>
<Grid x:Name="Dodupy" Height="135" Width="161" Tag="2" DataContext="{Binding Path=Feeds[0]}" >
<TextBlock Text="Muzyka"/>
</Grid>
<Grid Height="135" Width="161" Tag="3" DataContext="{Binding Path=Feeds[0]}">
<TextBlock Text="Kultura"/>
</Grid>
<Grid Height="135" Width="161" Tag="4" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<TextBlock Text="Sport"/>
</Grid>
<Grid Height="135" Width="161" Tag="5">
<TextBlock Text="O nas"/>
</Grid>
<Grid Height="135" Width="161" Tag="6">
<TextBlock Text="Audycja Autorskie"/>
</Grid>
<Grid Height="135" Width="161" Tag="7">
<TextBlock Text="Ekipa"/>
</Grid>
<Grid Height="135" Width="161" >
<TextBlock Text="Ramówka"/>
</Grid>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="Schedule" Width="606" Header="Ramówka" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<GridView x:Name="ScheduleContent" Height="519" Width="606" ItemClick="Contetnview_ItemClick">
<Grid Height="135" Width="161" >
<TextBlock Text="Ramówka"></TextBlock>
</Grid>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="Team" Width="606" Header="Ekipa" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<GridView x:Name="TeamContent" Height="519" Width="606" ItemClick="Contetnview_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="135" Width="161" >
<Image>
</Image>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="AuthorShow" Width="606" Header="Audycje Autorskie" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<GridView x:Name="AuthorShowContent" Height="519" Width="606" ItemClick="Contetnview_ItemClick">
<Grid Height="135" Width="161" >
<Image>
</Image>
</Grid>
</GridView>
</DataTemplate>
</HubSection>
<HubSection x:Name="AboutUs" Width="606" Header="O nas" IsHeaderInteractive="True" DataContext="{Binding Source=feedDataSource, Path=Feeds[0]}">
<DataTemplate>
<Grid x:Name="AboutUSContent" Height="519" Width="606" >
<TextBlock Text="TutajONAS"></TextBlock>
</Grid>
</DataTemplate>
</HubSection>
</Hub>
</Grid>
It seems that reason the music stops is because you are creating the stream in a page, and then moving away from the page which is causing everything you just allocated to go away.
I would recommend trying to create/play your media player object in the App.xaml.cs file.
This should live across page calls.

How to do validation for Combobox value to match the database value?

I'm create an module which is a Editing Bill module which will enable the user to edit the available in the database. I'm facing one validation problem which is that when the user don't want to edit the bill & click on the "Cancel" button will back to the listview to continue select another record. Here is my problem come as when the user didn't make any modification & accidentally click on the "Status" combo from "UNPAID" to "PAID" then directly quite. When re select the record then the record status value will become "PAID" instead of "UNPAID" which is the actual value.
How can I do so that when every time the user don't make any modification & return back to the listview will set back the default value for the combobox.
Thank you all for viewing this question & hope to receive reply :)
I will attach my code so that easily to refer:
XAML File
<Window x:Class="HouseWivesSavior.HomecareModule.EditBillRemainder"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="EditBillRemainder" Height="600" Width="800" Loaded="Window_Loaded">
<Window.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFFFFFF" Offset="0"/>
<GradientStop Color="#FFFF00FF" Offset="1"/>
</LinearGradientBrush>
</Window.Background>
<Window.Resources>
<DataTemplate x:Key="MyDataTemplate">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillName}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate2">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillDescription}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate3">
<Border BorderBrush="#FF000000" BorderThickness="1,1,0,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillAmount}"/>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate x:Key="MyDataTemplate4">
<Border BorderBrush="#FF000000" BorderThickness="1,1,1,1" Margin="-6,-2,-6,-2">
<StackPanel Margin="6,2,6,2">
<TextBlock Text="{Binding Path=BillDueDate, StringFormat='dd-MM-yyyy'}"/>
</StackPanel>
</Border>
</DataTemplate>
<Style x:Key="MyItemContainerStyle" TargetType="{x:Type ListViewItem}">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<!--<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />-->
</Style>
<!--DatePickerTextBoxFormat-->
<Style TargetType="{x:Type DatePickerTextBox}">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<TextBox x:Name="PART_TextBox" Text="{Binding Path=SelectedDate, StringFormat='dd-MM-yyyy', RelativeSource={RelativeSource AncestorType={x:Type DatePicker}}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListView Name="lvwBooks" Background="White" ItemsSource="{Binding}" Margin="131,130,4,6" ItemContainerStyle="{DynamicResource MyItemContainerStyle}">
<ListView.View>
<GridView>
<GridViewColumn Header="Bill Name" Width="100" CellTemplate="{DynamicResource MyDataTemplate}"/>
<GridViewColumn Header="Description" Width="250" CellTemplate="{DynamicResource MyDataTemplate2}"/>
<GridViewColumn Header="Amount" Width="160" CellTemplate="{DynamicResource MyDataTemplate3}"/>
<GridViewColumn Header="Due Date" Width="100" CellTemplate="{DynamicResource MyDataTemplate4}"/>
<GridViewColumn Header="Edit">
<GridViewColumn.CellTemplate>
<DataTemplate>
<UserControl>
<Hyperlink Click="InputBox_Click">Edit
<Hyperlink.Style>
<Style TargetType="{x:Type Hyperlink}">
<Setter Property="Hyperlink.IsEnabled" Value="False" />
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}}, Path=IsSelected}" Value="True">
<Setter Property="Hyperlink.IsEnabled" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</Hyperlink.Style>
</Hyperlink>
</UserControl>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<!-- It's important that this is in the end of the XAML as it needs to be on top of everything else! -->
<Grid x:Name="InputBox" Visibility="Collapsed">
<Grid Background="Black" Opacity="0.5" />
<Border
MinWidth="250"
Background="Orange"
BorderBrush="Black"
BorderThickness="1"
CornerRadius="0,40,0,40"
HorizontalAlignment="Center"
VerticalAlignment="Center" Height="493" Margin="130,30,120,38" Width="528">
<Canvas Height="446" Width="524">
<GroupBox Header="General Information" Height="141" HorizontalAlignment="Left" Margin="193,52,0,0" Name="groupBox1" VerticalAlignment="Top" Width="495" Canvas.Left="-173" Canvas.Top="-67">
<Canvas Background="WhiteSmoke" Opacity="1">
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="207,13,0,140" ResizeBehavior="PreviousAndNext" Width="2" Height="50" Canvas.Left="-3" Canvas.Top="48" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="6,6,0,0" Name="textBlock1" Text="Bill Name" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="215,65,0,0" Name="textBlock4" Text="Due Date" VerticalAlignment="Top" Grid.ColumnSpan="2" />
<GridSplitter HorizontalAlignment="Left" ResizeBehavior="PreviousAndNext"
Width="1" Background="#FFBCBCBC" Margin="206,63,0,9" />
<DatePicker Height="25" HorizontalAlignment="Right" Margin="0,80,157,0" Name="BillDueDatedatePicker" VerticalAlignment="Top" Width="115" Grid.ColumnSpan="2" Canvas.Left="215" Canvas.Top="6" Text="{Binding Path=BillDueDate, StringFormat='dd-MM-yyyy'}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" SelectedDateFormat="Short"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="7,29,0,0" Name="BillNameTxtBox" VerticalAlignment="Top" Width="458" Grid.ColumnSpan="2" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillName}"/>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,63,0,0" Name="textBlock8" Text="Bill Type" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="8,81,0,0" Name="BillTypeCboBox" VerticalAlignment="Top" Width="193" Canvas.Left="-5" Canvas.Top="8" Text="{Binding Path=BillTypes}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}">
<ComboBoxItem Content="Water" />
<ComboBoxItem Content="Electricity" />
<ComboBoxItem Content="Gas" />
<ComboBoxItem Content="Internet/broadband"/>
<ComboBoxItem Content="Others"/>
</ComboBox>
<TextBox Canvas.Left="62" Canvas.Top="3" Height="23" Name="textBox1" Width="120" Visibility="Visible" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillNo}"/>
</Canvas>
</GroupBox>
<GroupBox Header="Payment Information" Height="339" HorizontalAlignment="Left" Margin="193,202,0,0" Name="groupBox2" VerticalAlignment="Top" Width="495" Canvas.Left="-174" Canvas.Top="-81">
<Canvas Background="WhiteSmoke" Height="303" Visibility="Visible">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,17,0,0" Name="textBlock6" Text="Amount Due" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="7,75,0,0" Name="textBlock7" Text="Description" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="81,14,0,0" Name="BillAmountTxtBox" VerticalAlignment="Top" Width="120" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" Text="{Binding Path=BillAmount}"/>
<TextBox Height="148" HorizontalAlignment="Left" Margin="4,96,0,0" Name="BillDescriptionTxtBox" VerticalAlignment="Top" Width="471" VerticalScrollBarVisibility="Visible" SpellCheck.IsEnabled="True" TextWrapping="Wrap" AcceptsReturn="True" Text="{Binding Path=BillDescription}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}"/>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="6,46,0,0" Name="textBlock9" Text="Status" VerticalAlignment="Top" />
<ComboBox Height="23" HorizontalAlignment="Left" Margin="81,46,0,0" Name="BillStatusCboBox" VerticalAlignment="Top" Width="120" SelectionChanged="comboBox3_SelectionChanged" Text="{Binding Path=BillStatus}" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}" >
<ComboBoxItem Content="UNPAID" />
<ComboBoxItem Content="PAID" />
</ComboBox>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="215,14,0,0" Name="textBlock10" Text="Bill is Paid:" VerticalAlignment="Top" />
<DatePicker Text="{Binding Path=BillPaidDate}" Height="25" HorizontalAlignment="Left" Margin="212,37,0,0" Name="BillPaidDatedatePicker" VerticalAlignment="Top" Width="115" IsEnabled="false" DataContext="{Binding ElementName=lvwBooks, Path=SelectedItem}"/>
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="205,14,0,228" ResizeBehavior="PreviousAndNext" Width="2" />
<Separator Height="26" HorizontalAlignment="Left" Margin="7,250,0,0" Name="separator1" VerticalAlignment="Top" Width="470" />
<Button Content="Done" Height="23" HorizontalAlignment="Left" Margin="322,267,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="YesButton_Click" />
<Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="402,266,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="NoButton_Click" />
<GridSplitter Background="#FFBCBCBC" HorizontalAlignment="Left" Margin="207,13,0,140" ResizeBehavior="PreviousAndNext" Width="0" />
</Canvas>
</GroupBox>
</Canvas>
</Border>
</Grid>
</Grid>
</Window>
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace HouseWivesSavior.HomecareModule
{
/// <summary>
/// Interaction logic for EditBillRemainder.xaml
/// </summary>
public partial class EditBillRemainder : Window
{
public EditBillRemainder()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ShowData();
}
private void InputBox_Click(object sender, RoutedEventArgs e)
{
// CoolButton Clicked! Let's show our InputBox.
InputBox.Visibility = System.Windows.Visibility.Visible;
}
private void NoButton_Click(object sender, RoutedEventArgs e)
{
//ShowData();
// NoButton Clicked! Let's hide our InputBox.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var item = sender as ListViewItem;
if (item != null && item.IsSelected)
{
}
}
//Design
private void comboBox3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
////The logic for this will be stanger but in order to cope iwht the SelectionChange behavior.
//string s1 = BillStatusCboBox.SelectionBoxItem.ToString();
//// MessageBox.Show(s1);
//if (s1.Equals("UNPAID"))
//{
// BillPaidDatedatePicker.IsEnabled = true;
// BillPaidDatedatePicker.Text = DateTime.Now.ToString("d/MM/yyyy");
//}
//if (s1.Equals("PAID"))
//{
// BillPaidDatedatePicker.IsEnabled = false;
// //BillStatusCboBox.SelectedIndex = 0;
//}
ComboBoxItem currentItem = ((System.Windows.Controls.ComboBoxItem)BillStatusCboBox.SelectedItem);
if (currentItem.Content.Equals("PAID"))
{
BillPaidDatedatePicker.IsEnabled = true;
// BuilderupdateButton.Visibility = Visibility.Visible;
}
else {
BillPaidDatedatePicker.IsEnabled = false;
}
}
//Database
public void ShowData()
{
SqlConnection conn;
string connStr = ConfigurationManager.ConnectionStrings["house"].ConnectionString;
conn = new SqlConnection(connStr);
//SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
conn.Open();
SqlCommand comm = new SqlCommand("Select * from bill ORDER BY BillDueDate", conn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
lvwBooks.DataContext = dt.DefaultView;
}
private void YesButton_Click(object sender, RoutedEventArgs e)
{
Update();
// YesButton Clicked! Let's hide our InputBox and handle the input text.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
public void Update() {
SqlConnection conn;
SqlCommand cmdInsert;
String strUpdate;
string connStr = ConfigurationManager.ConnectionStrings["house"].ConnectionString;
conn = new SqlConnection(connStr);
strUpdate = "UPDATE bill SET BillName=#BillName, BillTypes=#BillTypes, BillDueDate=#BillDueDate, BillAmount=#BillAmount, BillStatus=#BillStatus, BillPaidDate=#BillPaidDate, BillDescription=#BillDescription WHERE BillNo='" + textBox1.Text + "' ";
cmdInsert = new SqlCommand(strUpdate, conn);
cmdInsert.Parameters.AddWithValue("#BillName", BillNameTxtBox.Text);
cmdInsert.Parameters.AddWithValue("#BillTypes", BillTypeCboBox.Text);
cmdInsert.Parameters.AddWithValue("#BillDueDate", DateTime.Parse(BillDueDatedatePicker.Text));
cmdInsert.Parameters.AddWithValue("#BillAmount", BillAmountTxtBox.Text);
cmdInsert.Parameters.AddWithValue("#BillStatus", BillStatusCboBox.Text);
//MessageBox.Show(BillPaidDatedatePicker.Text);
if (BillPaidDatedatePicker.Text.Equals(""))
{
cmdInsert.Parameters.AddWithValue("#BillPaidDate", "");
}
else {
cmdInsert.Parameters.AddWithValue("#BillPaidDate", DateTime.Parse(BillPaidDatedatePicker.Text));
}
// cmdInsert.Parameters.AddWithValue("#BillPaidDate", DateTime.Parse(empty));
cmdInsert.Parameters.AddWithValue("#BillDescription", BillDescriptionTxtBox.Text);
try
{
conn.Open();
int result = cmdInsert.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Bill Edited!!!");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally {
conn.Close();
}
}
}
}
For this case it would be better to user IDataErrorInfo interface instead of using ValiationRule since IDataErrorInfo will be handled inside ViewModel where you also have all the necessary database statements.
Here is a link to a tutorial explaining how to do validation with IDataErrorInfo.
http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/
Have fun :)
I solved it by like this:
Code-Behind:
The problem that I faced is NullReferenceException then I used a try..catch to catch the "NullReferenceException"
private void comboBox3_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem currentItem = ((System.Windows.Controls.ComboBoxItem)BillStatusCboBox.SelectedItem);
try
{
if (currentItem.Content.Equals("PAID"))
{
BillPaidDatedatePicker.IsEnabled = true;
// BuilderupdateButton.Visibility = Visibility.Visible;
}
else
{
BillPaidDatedatePicker.IsEnabled = false;
}
}
catch (NullReferenceException ex){ // At here which you can see.
//I purposely set it to do nothing when catch it.
}
Then when the user accidentally click on the "UPAID" to "PAID" & directly click on the cancel button will invoke "NoButton_Click" which will try to reload & select the value from the database:
private void NoButton_Click(object sender, RoutedEventArgs e)
{
ShowData(); // Invoke & select from database again.
// NoButton Clicked! Let's hide our InputBox.
InputBox.Visibility = System.Windows.Visibility.Collapsed;
}
I know by this way solving my problem will be quite inefficient but get the job done :) Which is fine to me.

Listbox item as Listbox should clear the selection of its item when other item's item is selected?

I have a ListBox as a ListboxItem in the mainlist. In one item that is ListBox I select an item. This selection should be cleared when I have another item selected from the other items ListBox. Code is as below:
<ListBox x:Name="lst" Grid.Row="3" BorderThickness="0" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ItemsSource="{Binding MessageCollection}" ScrollViewer.CanContentScroll="False" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Width="{Binding RelativeSource= {RelativeSource FindAncestor, AncestorType={x:Type Grid}},Path=ActualWidth}" HorizontalAlignment="Stretch">
<Border Background ="#ffffff" BorderBrush="#dddddd" BorderThickness="0,1,0,0" Height="30" >
<TextBlock Text="{Binding Date, StringFormat={}{0:dd MMMM yyyy}}" VerticalAlignment="Center" FontWeight="Bold" FontSize="12" FontFamily="Tahoma" Foreground="#7a7a7a" HorizontalAlignment="Center" />
</Border>
<ListBox x:Name="lstMsgs" HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden" HorizontalContentAlignment="Stretch" ItemsSource="{Binding MessageList}" SelectedItem="{Binding DataContext.SelectedMessage,Mode=TwoWay,ElementName=me}" Background="Transparent" BorderThickness="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Border x:Name="brdItem" BorderBrush="#dddddd" BorderThickness="0,1,0,0" >
<Border.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="#f1f1f1" Offset="0"/>
<GradientStop Color="#efefef" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
<Grid Height="30" HorizontalAlignment="Stretch" VerticalAlignment="Center" ScrollViewer.HorizontalScrollBarVisibility="Hidden" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="30" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="30" />
</Grid.ColumnDefinitions>
<Image x:Name="img" Grid.Column="1" Visibility="Collapsed" HorizontalAlignment="Center" Source="Images\icon1.png" Stretch="None" Margin="10,0,0,0" />
<TextBlock Text="Ershad Sheikh" VerticalAlignment="Center" Foreground="#2b2a2a" FontSize="12" Grid.Column="3" />
<TextBlock Text="{Binding GroupMessage}" HorizontalAlignment="Left" Foreground="#7a7a7a" FontSize="11" Grid.Column="5" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding Date, StringFormat={}{0: hh:mm:ss tt}}" FontWeight="Bold" FontSize="12" Foreground="#2378a0" Grid.Column="7" VerticalAlignment="Center" HorizontalAlignment="Right" />
</Grid>
</Border>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsReplyPresent}" Value="True">
<Setter TargetName="img" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True">
<Setter TargetName="brdItem" Property="Background" Value="#e5e9eb" >
</Setter>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="#e5e9eb"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/>
</ListBox.Resources>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="#e5e9eb"/>
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
Color="Transparent" />
</ListBox.Resources>
</ListBox>
You can explicitly null the SelectedItem whenever the ListBox loses focus, i.e you have to handle the LostFocus event.
You could add the event handler to the ListBox and handle the event in the code behind.
XAML Change:
<ListBox x:Name="lstMsgs" HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden" HorizontalContentAlignment="Stretch" ItemsSource="{Binding MessageList}" SelectedItem="{Binding DataContext.SelectedMessage,Mode=TwoWay,ElementName=me}" Background="Transparent" BorderThickness="0" LostFocus="lstMsgs_LostFocus">
Code Behind:
private void lstMsgs_LostFocus(object sender, RoutedEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox != null)
{
listBox.SelectedItem = null;
}
}
Method 2:
You could achieve the same result by using a DependencyProperty to handle the LostFocus event.
ListBoxExtension.cs
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public static class ListBoxExtension
{
public static readonly DependencyProperty NullSelectedItemOnLostFocusProperty =
DependencyProperty.RegisterAttached("NullSelectedItemOnLostFocus", typeof(bool), typeof(ListBoxExtension), new UIPropertyMetadata(false, OnNullSelectedItemOnLostFocusChanged));
public static bool GetNullSelectedItemOnLostFocus(DependencyObject d)
{
return (bool)d.GetValue(NullSelectedItemOnLostFocusProperty);
}
public static void SetNullSelectedItemOnLostFocus(DependencyObject d, bool value)
{
d.SetValue(NullSelectedItemOnLostFocusProperty, value);
}
private static void OnNullSelectedItemOnLostFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool nullSelectedItemOnLostFocus = (bool)e.NewValue;
ListBox listBox = d as ListBox;
if (listBox != null)
{
if (nullSelectedItemOnLostFocus)
listBox.LostFocus += NullSelectedItem;
else
listBox.LostFocus -= NullSelectedItem;
}
}
public static void NullSelectedItem(object sender, RoutedEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox != null)
{
listBox.SelectedItem = null;
}
}
}
}
XAML Change 1: Add namespace in which the ListBoxExtension class is present - xmlns:loc="clr-namespace:WpfApplication1"
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
XAML Change 2: Changing the DependencyProperty - loc:ListBoxExtension.NullSelectedItemOnLostFocus="True"
<ListBox x:Name="lstMsgs" HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden" HorizontalContentAlignment="Stretch" ItemsSource="{Binding MessageList}" SelectedItem="{Binding DataContext.SelectedMessage,Mode=TwoWay,ElementName=me}" Background="Transparent" BorderThickness="0" loc:ListBoxExtension.NullSelectedItemOnLostFocus="True">

Categories