I have sample XAML with TextBox code as:
XAML
<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Center"
Text="{Binding Path=Remarks, UpdateSourceTrigger=PropertyChanged}"
BorderThickness="0.5" Margin="0" Height="50" Background="Transparent" Foreground="White" />
<Button CommandParameter="{Binding ListExecActionId}"
Command="{Binding Source={StaticResource Locator}, Path=TaskPerformanceModel.ActivityAction_comment}"
Content="Save" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3,0,0,0" Height="Auto" />
View Model:
public string Remarks
{
get { return _remarks; }
set
{
if (!string.Equals(_remarks, value))
{
_remarks = value;
RaisePropertyChanged("Remarks");
}
}
}
ActivityAction_coment as follows
public RelayCommand<object> ActivityAction_comment
{
get
{
if (_ActivityAction_comment == null)
{
_ActivityAction_comment = new RelayCommand<object>((ExecActionId) => ActivityComment(ExecActionId));
}
return _ActivityAction_comment;
}
}
private void ActivityComment(object _id)
{
try
{
using (DataContext objDataContext = new DataContext(DBConnection.ConnectionString))
{
ListExecutionAction tblListExec = objDataContext.ListExecutionActions.Single(p => p.Id == Convert.ToInt32(_id));
**tblListExec.Remarks = Remarks; // Not getting Remarks value from Textbox**
objDataContext.SubmitChanges();
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "TaskExecution:ActivityComment");
}
}
I am unable to get textbox (Remarks) value in view model. Always getting "".
can any one help me out please.
For more clarity I am updating view:
<ListView.View>
<GridViewColumn >
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding ActionDescription}" Foreground="White" FontSize="16"></TextBlock>
<ToggleButton Name="button">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<TextBlock>Remarks!!</TextBlock>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False" Width="250" Height="100">
<StackPanel>
<TextBlock Background="LightBlue" Text="{Binding ActionDescription}"></TextBlock>
<TextBlock Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Text="Comments:" Foreground="White" Background="Transparent" />
<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Center"
Text="{Binding Path=Remarks, UpdateSourceTrigger=PropertyChanged}"
BorderThickness="0.5" Margin="0" Height="50"/>
<!--Text="{Binding Remarks, Mode=OneWayToSource}" Text="{Binding Path=Remarks, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding CollectionOfListQueue}" Background="Transparent" Foreground="White"-->
<Button CommandParameter="{Binding ListExecActionId}" Command="{Binding Source={StaticResource Locator}, Path=TaskPerformanceModel.ActivityAction_comment}" Content="Save" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3,0,0,0" Height="Auto" />
<Button Content="Cancel" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="2,0,0,0" Height="Auto" />
<!--</Grid>-->
</StackPanel>
</Popup>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
Bind to ActivityAction_comment and Remarks properties of the view model:
<Button CommandParameter="{Binding ListExecActionId}"
Command="{Binding DataContext.ActivityAction_comment, RelativeSource={RelativeSource AncestorType=ListView}}"
Content="Save" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3,0,0,0" Height="Auto" />
You need to the same for the Remarks binding
<TextBox Text="{Binding DataContext.Remarks, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=ListView}}" ... />
You should then be able to get the value in the TextBox using the Remarks source property:
private void ActivityComment(object _id)
{
try
{
using (DataContext objDataContext = new DataContext(DBConnection.ConnectionString))
{
ListExecutionAction tblListExec = objDataContext.ListExecutionActions.Single(p => p.Id == Convert.ToInt32(_id));
string remarks = Remarks;
objDataContext.SubmitChanges();
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "TaskExecution:ActivityComment");
}
}
Related
I have a ListView with two DataTemplate for items and headers.
Items from the ListView are binded to CollectionViewSource which looks like this:
<CollectionViewSource
x:Name="groupedItemsViewSource3"
Source="{Binding Groups2}"
IsSourceGrouped="true"
ItemsPath="Items"
d:Source="{Binding Groups, Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"/>
I can manage to get ListViewItem but I cant get control of its child controls.
My ListView looks like this:
<ListView
Margin="0,40,0,0"
Width="580"
HorizontalAlignment="Right"
x:Name="itemGridView1"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Grouped Items"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource2}}"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick" Background="White">
<ListView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Background="LightGray" Width="2500" Height="25">
<Border HorizontalAlignment="Stretch" BorderThickness="0,0,0,1" BorderBrush="Black">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Time}" Margin="10,0,0,0" Width="50" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
<TextBlock Text="{Binding LiveTime}" Foreground="{Binding LiveTimeBGColor}" Margin="10,0,0,0" Width="40" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
<TextBlock Text="{Binding TeamOne}" Margin="0,0,10,0" HorizontalTextAlignment="Right" Width="150" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
<Border Background="DarkGray" Width="35" Margin="0,0,2,0" Padding="15,0,0,0">
<TextBlock Text="{Binding ScoreTeamOne}" Width="30" Foreground="White" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
</Border>
<Border Background="DarkGray" Width="35" Padding="15,0,0,0" Margin="2,0,0,0">
<TextBlock Text="{Binding ScoreTeamTwo}" Foreground="White" Width="30" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
</Border>
<TextBlock Text="{Binding TeamTwo}" Margin="10,0,0,0" HorizontalAlignment="Left" Width="150" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
</StackPanel>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="0,0,0,2" Width="2500" Background="{Binding HeaderLiveBGColor}">
<Button Foreground="{ThemeResource ApplicationHeaderForegroundThemeBrush}"
AutomationProperties.Name="Group Title"
Click="Header_Click"
Style="{StaticResource TextBlockButtonStyle}" Width="2500">
<StackPanel Orientation="Horizontal" Width="2500">
<TextBlock Text="{Binding LeagueTitle}" Margin="10,0,0,0" Width="441.9" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid GroupPadding="0,0,20,0" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
Any idea how can I check if the rights child control was clicked?
What I want to eventually achieve is the handle a click based on the controls of the ListViewItem clicked.
To get the clicked item from ListViewItem
If you add break points to debug your code, you could know there's a ClickedItem in ItemClickEventArgs class object. The ClickedItem should be that you want.
Another way is using TwoWay Binding on the SelectedItem.
Both the two ways are included in the following code sample:
<Page.Resources>
<CollectionViewSource
x:Name="groupedItemsViewSource3"
Source="{Binding Groups2}"
IsSourceGrouped="true"
ItemsPath="Items" />
</Page.Resources>
<Grid>
<ListView
Margin="0,40,0,0"
Width="580"
HorizontalAlignment="Right"
x:Name="itemGridView1"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Grouped Items"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource3}}"
SelectedItem="{Binding SelectedSong,Mode=TwoWay}"
SelectionMode="Single"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemGridView_ItemClick" Background="White">
<ListView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Background="LightGray" Width="2500" Height="25">
<Border HorizontalAlignment="Stretch" BorderThickness="0,0,0,1" BorderBrush="Black">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Margin="10,0,0,0" Width="50" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
</StackPanel>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="0,0,0,2" Width="2500" Background="{Binding HeaderLiveBGColor}">
<Button Foreground="{ThemeResource ApplicationHeaderForegroundThemeBrush}"
AutomationProperties.Name="Group Title"
Style="{StaticResource TextBlockButtonStyle}" Width="2500">
<StackPanel Orientation="Horizontal" Width="2500">
<TextBlock Text="{Binding Key}" Margin="10,0,0,0" Width="441.9" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap" />
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid GroupPadding="0,0,20,0" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
</Grid>
public sealed partial class MainPage : Page
{
public ObservableCollection<SongGroup> Groups2 { get; set; }
private Song _SelectedSong;
public Song SelectedSong
{
get { return _SelectedSong; }
set
{
_SelectedSong = value;
}
}
public MainPage()
{
this.InitializeComponent();
Groups2 = GenerateData();
this.DataContext = this;
}
private ObservableCollection<SongGroup> GenerateData()
{
ObservableCollection<SongGroup> songGroups = new ObservableCollection<SongGroup>();
ObservableCollection<Song> songs = new ObservableCollection<Song>();
songs.Add(new Song() { Title = "Song1" });
songs.Add(new Song() { Title = "Song2" });
songGroups.Add(new SongGroup() { Key = "A", Items = songs });
ObservableCollection<Song> songs2 = new ObservableCollection<Song>();
songs2.Add(new Song() { Title = "Song2_1" });
songs2.Add(new Song() { Title = "Song2_2" });
songGroups.Add(new SongGroup() { Key = "B", Items = songs2 });
return songGroups;
}
private void ItemGridView_ItemClick(object sender, ItemClickEventArgs e)
{
var song = e.ClickedItem;
}
}
public class Song
{
public string Title { get; set; }
}
public class SongGroup
{
public string Key { get; set; }
public ObservableCollection<Song> Items { get; set; }
}
How i can get items as string in item view modal.
I have tried the following but they are not giving me correct output.
if (Opf.ShowDialog() == true)
{
StreamWriter swa = new StreamWriter(Opf.FileName);
using (swa)
{
for (int i = 0; i < PlayList.Items.Count; i++)
{
var ix = PlayList.Items.GetItemAt(i).ToString();
swa.WriteLine(ix);
}
}
MessageBox.Show("List Saved.");
}
It gives me
Wss.ItemViewModal
Wss.ItemViewModal
Wss.ItemViewModal
Wss.ItemViewModal
How i can get item from my listbox. My listbox xaml code
<ListBox Name="PlayList" Margin="0,50,0,30" Style="{DynamicResource ListBoxStyle1}" Background="Transparent" BorderThickness="0" Foreground="White" ItemsSource="{Binding Items, Mode=TwoWay}" MouseDoubleClick="PlayList_MouseDoubleClick">
<!--Style="{DynamicResource ListBoxStyle1}" SelectionChanged="PlayList_SelectionChanged"-->
<ListBox.ItemTemplate >
<DataTemplate DataType="{x:Type local:ItemViewModel}">
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type Label}">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</Grid.Resources>
<Label Content="{Binding Sname}" FontSize="20" Foreground="White" x:Name="SongNameList" Margin="0" HorizontalAlignment="Left" Width="193"/>
<Label Content="{Binding Duration}" FontSize="14" HorizontalContentAlignment="Center" Foreground="Orange" x:Name="DurationList" Margin="189,0,0,0" HorizontalAlignment="Left" Width="62"/>
<Label Content="{Binding Isvid}" FontSize="20" HorizontalContentAlignment="Right" Foreground="DeepPink" x:Name="VideoC" Margin="0,0,300,0" HorizontalAlignment="Right" Width="55"/>
<Label Content="{Binding Format }" FontSize="12" HorizontalContentAlignment="Right" Foreground="Orange" x:Name="Format" Margin="0,0,220,0" HorizontalAlignment="Right" Width="50"/>
<Label Content="{Binding YTL}" FontSize="20" HorizontalContentAlignment="Right" Foreground="White" x:Name="YT" Margin="0,0,100,0" HorizontalAlignment="Right" Width="148"/>
<Label Content="{Binding SNN}" FontSize="20" HorizontalContentAlignment="Right" Foreground="SkyBlue" x:Name="SN" Margin="0" HorizontalAlignment="Right" Width="95"/>
<Label Content="{Binding VPath }" FontSize="20" Foreground="Green" x:Name="Path" Margin="256,0,332,0"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Anything more you want to ask just comment.
Thank you very much .
You can override the method ToString() of your ItemViewModel class.
public class ItemViewModel
{
...
public override string ToString()
{
return $"ItemViewModel: {Sname} {Duration} {Isvid} {Format } {YTL} {SNN} {VPath}";
}
...
}
if not overriden in class, ToString() returns class name with namespace which heppen to be Wss.ItemViewModal. Overriding ToString() for export purposes is hardly optimal solution - export formats can vary for a single class! It makes more sense to implement IFormattable in ItemViewModal and specify format.
Alternatively: don't use ToString and list all properties which should be exported:
if (Opf.ShowDialog() == true)
{
using (StreamWriter swa = new StreamWriter(Opf.FileName))
{
foreach(ItemViewModal vm in PlayList.Items)
{
var ix = vm.Sname + " " + vm.Duration;
swa.WriteLine(ix);
}
}
MessageBox.Show("List Saved.");
}
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>
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.
I'm working on a WIN 8.1 App. In my App I have a ListView where I'm binding a observable collection from a ViewModel. So far everything works fine. The Problem is, that in the Background all the Data will be loaded correctly, but my ListView displays after approximately 40 elements, from the beginning... In the Background the right Object is selected and 80 Objects are loaded.
Could it be a Problem with the Scrolling?
Does anyone know, how to solve this issue?
From an other Page, i navigate to the Page with the ListView:
private void ShowReturnData()
{
ReturnViewModel retVM = new ReturnViewModel(_navigationService, SelectedTour);
_navigationService.NavigateTo(ViewModelLocator.ReturnPageKey, retVM);
}
In my ViewModel Constructor, I add my data to the observable Collection:
I'm working with MVVMlight.
Properties (ObservableCollection, SelectedItem):
--> observable Collection
/// <summary>
/// The <see cref="Data" /> property's name.
/// </summary>
public const string DataPropertyName = "Data";
private ObservableCollection<ReturnData> _myProperty = new ObservableCollection<ReturnData>();
/// <summary>
/// Sets and gets the Data property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ObservableCollection<ReturnData> Data
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
_myProperty = value;
RaisePropertyChanged(DataPropertyName);
}
}
--> SelectedItem
/// <summary>
/// The <see cref="SelectedItem" /> property's name.
/// </summary>
public const string SelectedItemPropertyName = "SelectedItem";
private ReturnData _selectedItem = null;
/// <summary>
/// Sets and gets the SelectedTour property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ReturnData SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem == value)
{
return;
}
if (_selectedItem != null)
{
_selectedItem.IsFirstItem = false;
_selectedItem.IsLastItem = false;
}
_selectedItem = value;
if (_selectedItem != null)
{
setIsFirstOrLastItem(Data.IndexOf(_selectedItem));
}
RaisePropertyChanged(SelectedItemPropertyName);
}
}
ViewModel Constructor:
public ReturnViewModel(INavigationService navigationService, TourDetailData tourDetails)
{
//Services
_navigationService = navigationService;
//Commands
PrevPageCommand = new RelayCommand(GoToPrevPage);
TourDetails = tourDetails;
TourCustomerName = "Tour " + tourDetails.Tour + " > " + tourDetails.AccountName;
Data = new ObservableCollection<ReturnData>(from i in TourDetails.ReturnData orderby Convert.ToInt32(i.ItemId) select i);
}
XAML:
<ListView x:Name="lvItems"
Grid.Row="2"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
ItemTemplate="{StaticResource ReturnDataTemplate}"
ItemContainerStyle="{StaticResource ReturnDataListViewItemStyle}"
ItemsSource="{Binding Data}"
Margin="0,5,0,0"
Loaded="lvItems_Loaded">
</ListView>
DataTemplate:
<DataTemplate x:Key="ReturnDataTemplate">
<Grid x:Name="grid" d:DesignWidth="1344.53" d:DesignHeight="123.228">
<Grid.Resources>
<converter:SelectionConverter x:Key="SelectionConverter" Context="{Binding}" />
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="450*"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Rectangle Grid.Row="0" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="Collapsed"/>
<Rectangle Grid.Row="2" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="Collapsed"/>
<!--<Rectangle Grid.Row="0" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="{Binding IsFirstItem, Converter={StaticResource BoolToVisibilityConverter}}"/>
<Rectangle Grid.Row="2" Grid.ColumnSpan="5" Height="100" Fill="LightGray" Visibility="{Binding IsLastItem, Converter={StaticResource BoolToVisibilityConverter}}"/>-->
<Rectangle Grid.Row="1" Fill="{StaticResource OrangeHighlight}" Visibility="{Binding IsDirty, Converter={StaticResource BoolToVisibilityConverter}}"/>
<StackPanel Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" Margin="15,0">
<TextBlock TextWrapping="Wrap" FontSize="42.667" FontFamily="Segoe UI" Text="{Binding ItemId}" FontWeight="SemiBold"/>
<TextBlock TextWrapping="Wrap" Text="{Binding ItemName}" FontSize="32" FontFamily="Segoe UI"/>
</StackPanel>
<!--<TextBox x:Name="tbxReturn" Grid.Row="1" TextWrapping="Wrap" Grid.Column="2" FontFamily="Segoe UI" FontSize="42.667" Text="{Binding Return}" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" PreventKeyboardDisplayOnProgrammaticFocus="True" DoubleTapped="tbxReturn_DoubleTapped" GotFocus="tbxReturn_GotFocus" />-->
<TextBox x:Name="tbxReturn" Grid.Row="1" TextWrapping="Wrap" Grid.Column="2" FontFamily="Segoe UI" FontSize="42.667" Text="{Binding Return}" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" DoubleTapped="tbxReturn_DoubleTapped" GotFocus="tbxReturn_GotFocus" InputScope="CurrencyAmountAndSymbol" Foreground="#FF520164" />
<TextBox x:Name="tbxMold" Grid.Row="1" TextWrapping="Wrap" Text="{Binding Mildew}" Grid.Column="3" FontFamily="Segoe UI" FontSize="42.667" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" DoubleTapped="tbxMold_DoubleTapped" Tapped="tbxMold_Tapped" GotFocus="tbxMold_GotFocus" InputScope="CurrencyAmountAndSymbol" Foreground="#FF019E90" />
<TextBox x:Name="tbxCredit" Grid.Row="1" TextWrapping="Wrap" Text="{Binding Credit}" Grid.Column="4" FontFamily="Segoe UI" FontSize="42.667" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource TextBoxStyleValues}" DoubleTapped="tbxCredit_DoubleTapped" Tapped="tbxCredit_Tapped" GotFocus="tbxCredit_GotFocus" InputScope="CurrencyAmountAndSymbol" Foreground="#FF005C9C" />
<!--<Button Grid.Row="1" Content="+" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="2" Height="100" Margin="0,-100,0,0" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.IncreaseReturnCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="-" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Grid.Column="2" Margin="0,0,0,-100" Height="100" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.DecreaseReturnCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="+" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="3" Height="100" Margin="0,-100,0,0" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.IncreaseMildewCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="-" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Grid.Column="3" Margin="0,0,0,-100" Height="100" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.DecreaseMildewCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="+" HorizontalAlignment="Stretch" VerticalAlignment="Top" Grid.Column="4" Height="100" Margin="0,-100,0,0" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.IncreaseCreditCommand, ElementName=lvItems}" Opacity="0.9"/>
<Button Grid.Row="1" Content="-" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Grid.Column="4" Margin="0,0,0,-100" Height="100" FontSize="48" Style="{StaticResource NumUpDownButtonStyle}" Visibility="{Binding ElementName=lvItems, Path=DataContext.SelectedItem, ConverterParameter=Selected, Converter={StaticResource SelectionConverter}}" Command="{Binding DataContext.DecreaseCreditCommand, ElementName=lvItems}" Opacity="0.9"/>-->
</Grid>
</DataTemplate>
Style:
<Style x:Key="ReturnDataListViewItemStyle" TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<ListViewItemPresenter x:Name="listViewItemPresenter" d:DesignWidth="938.908" d:DesignHeight="103.083"
ContentMargin="0"
DragOpacity="{ThemeResource ListViewItemDragThemeOpacity}"
DisabledOpacity="{ThemeResource ListViewItemDisabledThemeOpacity}"
HorizontalContentAlignment="Stretch"
Padding="0"
PointerOverBackgroundMargin="1"
ReorderHintOffset="{ThemeResource ListViewItemReorderHintThemeOffset}"
SelectionCheckMarkVisualEnabled="False"
SelectedBorderThickness="0"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="15,0,0,0"
SelectedForeground="Black"
SelectedPointerOverBackground="{StaticResource OrangeBackground}"
SelectedPointerOverBorderBrush="{StaticResource OrangeBackground}"
SelectedBackground="{StaticResource OrangeBackground}"
DataContext="{Binding SelectedItem}"
Content="{Binding Mode=OneWay}"
ContentTransitions="{TemplateBinding ContentTransitions}"
PlaceholderBackground="{StaticResource BackgroundGray}">
</ListViewItemPresenter>
</ControlTemplate>
</Setter.Value>
</Setter>
<!--<Setter Property="ContentTemplate" Value="{StaticResource ReturnDataTemplate}"/>-->
</Style>
In the Code behind of the XAML Page, I added the behavior of the ScrollViewer:
private void lvItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SetScrollViewer();
}
private async void SetScrollViewer()
{
if (lvItems.SelectedItem == null)
return;
var item = lvItems.SelectedItem;
var listViewItem = (FrameworkElement)lvItems.ContainerFromItem(item);
if (listViewItem == null)
{
lvItems.ScrollIntoView(item);
}
while (listViewItem == null)
{
await Task.Delay(1);
listViewItem = (FrameworkElement)lvItems.ContainerFromItem(item);
}
var topLeft =
listViewItem
.TransformToVisual(lvItems)
.TransformPoint(new Point()).Y;
var lvih = listViewItem.ActualHeight;
var lvh = lvItems.ActualHeight;
var desiredTopLeft = (lvh - lvih) / 2.0;
var desiredDelta = topLeft - desiredTopLeft;
// Calculations relative to the ScrollViewer within the ListView
var scrollViewer = lvItems.GetFirstDescendantOfType<ScrollViewer>();
var currentOffset = scrollViewer.VerticalOffset;
var desiredOffset = currentOffset + desiredDelta;
//scrollViewer.ScrollToVerticalOffset(desiredOffset);
// better yet if building for Windows 8.1 to make the scrolling smoother use:
scrollViewer.ChangeView(null, desiredOffset, null);
}