C# with WPF - Creating a grid of buttons resizable at runtime - c#

I want to implement the following: I have an empty window in the beginning with 3 buttons. When I click a button, I want to generate Size*Size buttons in the window. For button 1, Size=6, for button 2 Size=8 and for button 3 Size=0, so I thought I'd create a UniformGrid and bind its size to Size, so I can change the number of buttons present. Initially, Size would be 0, so no buttons can be seen, then when Size changes, the buttons appear. This, however, doesn't work. I'm trying:
<Window x:Class="project.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="500" Width="700">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Menu Grid.Column="1" Margin="38,0,187,430" Background="White">
<MenuItem Header="Level 1" FontFamily="Roboto" Height="32" Width="65"
Command="{Binding Lvl1Command}"/>
<MenuItem Header="Level 2" FontFamily="Roboto" Height="32" Width="65"
Command="{Binding Lvl2Command}"/>
<MenuItem Header="Level 3" FontFamily="Roboto" Height="32" Width="65"
Command="{Binding Lvl3Command}"/>
</Menu>
<ItemsControl Grid.Column="2" ItemsSource="{Binding Fields}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="{Binding Size}" Columns="{Binding Size}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Focusable="False" RenderTransformOrigin="0.5, 0.5"
Width="30" Height="25" FontSize="24" FontWeight="Bold">
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
Size is initially 0, Lvl1Command changes Size to 6, Lvl2Command to 8 etc. Fields is just a data structure storing some properties that will affect the style of the button. How could/should I modify this so that when Size changes, the number of appearing Buttons does too? Thank you!
EDIT
In the ViewModel constructor:
Lvl1Command = new DelegateCommand(param => { SetUpGame(MLModel.Level.Easy); });
Lvl2Command = new DelegateCommand(param => { SetUpGame(MLModel.Level.Medium); });
Lvl3Command = new DelegateCommand(param => { SetUpGame(MLModel.Level.Hard); });
And SetUpGame() looks like this (Field included):
private void SetUpGame(MLModel.Level level)
{
UpCommand = new DelegateCommand(param => { _model.MoveUp(); RefreshTable(); });
DownCommand = new DelegateCommand(param => { _model.MoveDown(); RefreshTable(); });
LeftCommand = new DelegateCommand(param => { _model.MoveLeft(); RefreshTable(); });
RightCommand = new DelegateCommand(param => { _model.MoveRight(); RefreshTable(); });
// időzítő létrehozása
_timer = new DispatcherTimer();
_timer.Interval = TimeSpan.FromSeconds(1);
_timer.Tick += new EventHandler(Timer_Tick);
_timer.Start();
_model.SetLevel(level);
_model.NewGame();
Fields = new ObservableCollection<MLField>();
for (Int32 i = 0; i < _model.Table.Size; i++)
{
for (Int32 j = 0; j < _model.Table.Size; j++)
{
Fields.Add(new MLField
{
Text = _model.Table[i, j],
X = i,
Y = j,
Number = i * _model.Table.Size + j
});
}
}
RefreshTable();
}
And then Size:
public Int32 Size { get { return _model.Size; } }

The ViewModel must implement INotifyPropertyChanged. Add this code:
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Then, if you want to raise notifications for changes on the Size property, write it this way:
public int Size
{
get { return _Size; }
set
{
if (_Size != value)
{
_Size = value;
NotifyPropertyChanged();
}
}
}
private int _Size;
Also, the Fields collection is initially null, and when you instantiate it in the SetupGame, no notification is raised so the View is still bound to the null reference. You have 2 options:
1) initialize the Fields collection in the constructor. This way, when the ViewModel is passed to the View, the collection is ready to be bound to the ItemsControl. It is not necessary to fill the collection in the constructor, just to instantiate it.
2) implement the Fields property in the same way the Size is:
public ObservableCollection<MLField> Fields
{
get { return _Fields; }
set
{
if (_Fields != value)
{
_Fields = value;
NotifyPropertyChanged();
}
}
}
private ObservableCollection<MLField> _Fields;
This way, you can set a new instance of the collection every time you want, and the ItemsControl binding will update consequently.

Related

C# XAML UWP - MenuFlyoutItem List not updating consistently in MenuFlyoutSubItem

this is probably a simple solution - its just a bit long to explain.
I add custom list view items to a ListView at run-time. Each ListView item has a Name, a Bool and a button. The button when clicked displays a Flyout menu which has subitem menu as shown in the image. The subitem menu should only display the name of all other items not itself. The correct behavior is shown in the first image as the "Item 4" menu button was clicked we only see Items 0 to 3 listed in the submenu.
The issue is that if i navigate to a submenu and then later add new items to the listbox, the new items never appear in the submenu for the older items previously navigated to. Like in the image below, where i clicked Item 1 button but only Item 0 and Item 2 are listed and for some reason Items 3 and 4 are not.
Firstly there is a complete minimum VS2019 solution demonstrating the behavior i'm describing above on GitHub here, though i have summarised what i think are the key bits of code below.
Non-boiler plate XAML header (MainPage.Xaml)
xmlns:local="using:DynamicFlyoutMenuTest.ViewModels"
The main ListView defintion and its DataTemplate as well as a button to add ListView items at run-time:
<StackPanel>
<Button Name="AddCustomListItemBtn" Click="AddCustomListItemBtn_Click">Add Custom ListItem</Button>
<ListView
Name="LayerListBox"
Height="Auto"
BorderBrush="{ThemeResource SystemBaseLowColor}"
BorderThickness="1.0"
ItemsSource="{x:Bind ViewModel.MyCustomListItems}">
<ListView.HeaderTemplate>
<DataTemplate>
<Grid Padding="2" Background="{ThemeResource SystemBaseLowColor}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="190" />
<ColumnDefinition Width="132" />
</Grid.ColumnDefinitions>
<TextBlock Style="{ThemeResource CaptionTextBlockStyle}" Text="Name" />
<TextBlock
Grid.Column="1"
Style="{ThemeResource CaptionTextBlockStyle}"
Text="Active" />
</Grid>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate x:Name="TableDataTemplate" x:DataType="local:MyCustomListItem">
<Grid Height="48" AutomationProperties.Name="{x:Bind ItemName}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="190" />
<ColumnDefinition Width="132" />
<ColumnDefinition Width="132" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0"
Padding="10"
VerticalAlignment="Center"
Text="{x:Bind ItemName, Mode=OneWay}" />
<CheckBox
Grid.Column="1"
VerticalAlignment="Center"
IsChecked="{x:Bind isEditing, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Button
Name="exportLayerButton"
Grid.Column="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Center">
<Button.Flyout>
<MenuFlyout Opening="MenuFlyout_Opening">
<MenuFlyoutItem
Name="Action1Btn"
Click="Action1Btn_Click"
Text="Action 1" />
<MenuFlyoutItem
Name="Action2Btn"
Click="Action2Btn_Click"
Text="Action 2" />
<MenuFlyoutSubItem x:Name="SubActionsBtn" Text="Choose Sub Action">
<MenuFlyoutItem Name="NoSubActionBtn" Text="None" />
</MenuFlyoutSubItem>
</MenuFlyout>
</Button.Flyout>
<Polygon
Fill="Black"
Points="0,0 6,4,0,8"
Stroke="Black" />
</Button>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
MainPage.xaml.cs - Add Item to List and Update Flyout Sub Menu Items
private void MenuFlyout_Opening(object sender, object e)
{
//make MenuFlyoutSubItem list all Items in ListView except the one triggering this function
var menuFlyout = sender as MenuFlyout;
// get the menu list we want to add to
MenuFlyoutSubItem menuSubItems = menuFlyout.Items.Where(x => x.Name == "SubActionsBtn").FirstOrDefault() as MenuFlyoutSubItem;
// get the active maplayerlistitem (that triggered this menu opening event)
MyCustomListItem myCustomListItem = (menuFlyout.Target as Button).DataContext as MyCustomListItem;
menuSubItems.Items.Clear();
foreach (var targetItem in ViewModel.MyCustomListItems)
{
if (myCustomListItem.ItemName != targetItem.ItemName)
{
var tItem = new MenuFlyoutItem();
tItem.Text = targetItem.ItemName.ToString();
//tItem.Click += new Windows.UI.Xaml.RoutedEventHandler(DoSomethingBtn_Click);
menuSubItems.Items.Add(tItem);
}
}
}
private void AddCustomListItemBtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
// Update ListView
var newItem = new MyCustomListItem();
newItem.ItemName = "Item " + ViewModel.MyCustomListItems.Count.ToString();
newItem.isEditing = false;
ViewModel.MyCustomListItems.Add(newItem);
}
MainViewModel.cs
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Microsoft.Toolkit.Mvvm.ComponentModel;
namespace DynamicFlyoutMenuTest.ViewModels
{
public class MainViewModel : ObservableObject
{
public ObservableCollection<MyCustomListItem> MyCustomListItems = new ObservableCollection<MyCustomListItem>();
public MainViewModel()
{
}
}
public class MyCustomListItem : INotifyPropertyChanged
{
public MyCustomListItem()
{
}
private bool _isEditing;
public bool isEditing
{
get { return _isEditing; }
set
{
_isEditing = value;
NotifyPropertyChanged(this, "isEditing");
}
}
private string _itemName;
public string ItemName
{
get { return _itemName; }
set
{
_itemName = value;
NotifyPropertyChanged(this, "ItemName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(object sender, string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(sender, e);
}
}
}
}
EDIT
You can view the issue in video at https://www.youtube.com/watch?v=yPNNtsS-n5Q
You can reproduce the issue from the GitHub source by
adding 3 items to the ListView using the "Add..." button.
Navigating to the submenuFlyout of each ListViewItem
Add 2 more Listview Items using the "Add..." button
navigate to the submenuFlyout of the two new items and finally
navigate to submenuFlyout of the original 3 items and see that they haven't updated to reflect the additional ListView items added.
I found a workaround by removing the exsiting MenuFlyoutSubItem and adding a new one each time the Flyout is opened. So it's not ideal, but it does work.
If anyone has as an actual solution, id be happy to mark it as such.
Otherwise here is the workaround:
private void MenuFlyout_Opening(object sender, object e)
{
//make MenuFlyoutSubItem list all Items in ListView except the one triggering this function
var menuFlyout = sender as MenuFlyout;
// get the menu list we want to add to
MenuFlyoutSubItem menuSubItems = menuFlyout.Items.Where(x => x.Name == "SubActionsBtn").FirstOrDefault() as MenuFlyoutSubItem;
// get the active maplayerlistitem (that triggered this menu opening event)
MyCustomListItem myCustomListItem = (menuFlyout.Target as Button).DataContext as MyCustomListItem;
menuFlyout.Items.Remove(menuSubItems);
menuSubItems = new MenuFlyoutSubItem();
menuSubItems.Name = "SubActionsBtn";
menuSubItems.Text = "Choose Sub Action";
foreach (var targetItem in ViewModel.MyCustomListItems)
{
if (myCustomListItem.ItemName != targetItem.ItemName)
{
var tItem = new MenuFlyoutItem();
tItem.Text = targetItem.ItemName.ToString();
//tItem.Click += new Windows.UI.Xaml.RoutedEventHandler(DoSomethingBtn_Click);
menuSubItems.Items.Add(tItem);
}
}
menuFlyout.Items.Add(menuSubItems);
}

c# uwp gridview items zindex

In UWP I have GridView. That GridView has ItemTemplate like this:
<Page.Resources>
<DataTemplate x:Key="Template" x:DataType="local:ModelClass">
<local:CustomUserControl
Model="{x:Bind Mode=OneWay}"/>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<GridView x:Name="gvMain" ItemTemplate="{StaticResource Template}" SelectionChanged="gvMain_SelectionChanged">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid Orientation="Vertical"
Margin="0,0,0,-10"
MaximumRowsOrColumns="1"
ItemWidth="50"
ItemHeight="50"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
</GridView>
</Grid>
The usercontrol is like this:
<Grid x:Name="gridMain" Width="50" Height="50">
<Grid VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0, 0, -10, 0" Width="20" Height="20" Background="Pink"/>
</Grid>
And in codebehind:
public ModelClass Model
{
get { return (ModelClass)GetValue(ModelProperty); }
set { SetValue(ModelProperty, value); SetBackground(); }
}
public static readonly DependencyProperty ModelProperty =
DependencyProperty.Register("Model", typeof(ModelClass), typeof(CustomUserControl), new PropertyMetadata(new ModelClass()));
private void SetBackground()
{
if (Model == null)
{
return;
}
gridMain.Background = Model.BackgroundColor;
}
public CustomUserControl()
{
this.InitializeComponent();
}
I am populating the GridView like this:
List<ModelClass> list = new List<ModelClass>();
ModelClass mc = new ModelClass();
mc.BackgroundColor = new SolidColorBrush(Colors.Red);
ModelClass mc1 = new ModelClass();
mc1.BackgroundColor = new SolidColorBrush(Colors.Blue);
ModelClass mc2 = new ModelClass();
mc2.BackgroundColor = new SolidColorBrush(Colors.Yellow);
ModelClass mc3 = new ModelClass();
mc3.BackgroundColor = new SolidColorBrush(Colors.Green);
list.Add(mc);
list.Add(mc1);
list.Add(mc2);
list.Add(mc3);
gvMain.ItemsSource = list;
And what it looks like is this:
On each item there is a small square in upper right corner, colored in pink.
When I click on some item, I want that item to overlap every other items, so my pink square will be visible.
How to change Z-index of GridView items in this case?
How to change Z-index of GridView items in this case?
If you want to change the GridViewItem's Z-Index, you might think about using canvas relevant panel as the GridView's ItemsPanel.
Then, in your SelectionChanged event handler method, you could use the Canvas.SetZIndex(UIElement, index) method to set current selected item's Canvas.ZIndex. It would get your effect that you want.
But, if you used the general Canvas control as the GridView's ItemsPanel. You would find that the items would not be shown as the general items list.
As a result, in your case, you also would need to define your custom panel. You could need to rearrange the items in it.
I've made a simple for your reference:
<GridView x:Name="gvMain" SelectionChanged="gvMain_SelectionChanged">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<local:CustomPanel></local:CustomPanel>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridViewItem >
<Rectangle Fill="Red" Width="50" Height="50"></Rectangle>
</GridViewItem>
<GridViewItem >
<Rectangle Fill="Blue" Width="50" Height="50" ></Rectangle>
</GridViewItem>
<GridViewItem>
<Rectangle Fill="Yellow" Width="50" Height="50"></Rectangle>
</GridViewItem>
</GridView>
public class CustomPanel:Canvas
{
protected override Size MeasureOverride(Size availableSize)
{
Size s = base.MeasureOverride(availableSize);
foreach (UIElement element in this.Children)
{
element.Measure(availableSize);
}
return s;
}
protected override Size ArrangeOverride(Size finalSize)
{
this.Clip = new RectangleGeometry { Rect = new Rect(0, 0, finalSize.Width, finalSize.Height) };
Double position = 0d;
foreach (UIElement item in this.Children)
{
if (item == null)
continue;
Size desiredSize = item.DesiredSize;
if (double.IsNaN(desiredSize.Width) || double.IsNaN(desiredSize.Height)) continue;
var rect = new Rect(0, position, desiredSize.Width, desiredSize.Height);
item.Arrange(rect);
TranslateTransform compositeTransform = new TranslateTransform();
compositeTransform.X = position / 2;
item.RenderTransform = compositeTransform;
position += desiredSize.Width;
}
return finalSize;
}
}
private void gvMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
GridViewItem item = (sender as GridView).SelectedItem as GridViewItem;
if (item != null)
{
Canvas.SetZIndex(item,index);
}
}
This just is a simple code sample, you could do more custom behavior in your custom panel.
The following are the effect screenshots:

Binding all System Colors to a ListBox

I'd like to bind all Windows.UI.Colors to a ListBox (ListView?) in a XAML Page, in a Universal Windows App (for Windows 10, in Visual Studio 2015).
I found this way to get all system colors:
Dictionary<string, Windows.UI.Color> Colors()
{
var _Colors = typeof(Windows.UI.Colors)
// using System.Reflection;
.GetRuntimeProperties()
.Select(c => new
{
Color = (Windows.UI.Color)c.GetValue(null),
Name = c.Name
});
return _Colors.ToDictionary(x => x.Name, x => x.Color);
}
I don't know how to bind it to a ListBox
<ListBox ItemsSource="{x:Bind colors}" >
</ListBox>
Ideally the list item text should be the color name, and the list item background the color value.
An alternative approach to #Romasz's answer:
Change the Color() method to a property, and return a dictionary with SolidColorBrush values instead of Color like so:
public Dictionary<string, SolidColorBrush> Colors
{
get
{
var _Colors = typeof(Windows.UI.Colors)
// using System.Reflection;
.GetRuntimeProperties()
.Select(c => new
{
Color = new SolidColorBrush((Windows.UI.Color)c.GetValue(null)),
Name = c.Name
});
return _Colors.ToDictionary(x => x.Name, x => x.Color);
}
}
Then, in the XAML, change the list box to this:
<ListBox ItemsSource="{x:Bind Colors}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="{Binding Value}">
<TextBlock Text="{Binding Key}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
There is couple of things you need to improve about binding (and I would advise to read some more at MSDN). As for your code - in xaml you will need to declare how your ItemTemplate will look like and bind to a property within DataContext. You will also need probably a converter to convert Color to Brush:
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemsSource="{Binding MyColors}">
<ListView.Resources>
<local:ColorToBrush x:Key="ColorToBrush"/>
</ListView.Resources>
<ListView.ItemTemplate>
<DataTemplate>
<Border Background="{Binding Color, Converter={StaticResource ColorToBrush}}">
<TextBlock Text="{Binding Name}"/>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
And the code behind - converter class, the suitable property and setting DataContext in constructor:
public class ColorToBrush : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language) => new SolidColorBrush((Windows.UI.Color)value);
public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); }
}
public sealed partial class MainPage : Page
{
// this is the shortcut of {get { return ... }}
public Array MyColors => typeof(Windows.UI.Colors).GetRuntimeProperties()
.Select(c => new
{
Color = (Windows.UI.Color)c.GetValue(null),
Name = c.Name
}).ToArray();
public MainPage()
{
this.InitializeComponent();
DataContext = this;
}
}
Of course you can also bind to Dictionary, then you will have to exchange in XAML bindings: Name -> Key and Color -> Value.
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
List<SystemColor> legacyBrushes = new List<SystemColor>();
foreach(var b in this.LegacyBrushes)
{
SystemColor c = new SystemColor();
c.ColorName = b;
c.ColorBrush = Application.Current.Resources[b] as SolidColorBrush;
legacyBrushes.Add(c);
}
foreach (var b in this.SystemBrushes)
{
SystemColor c = new SystemColor();
c.ColorName = b;
c.ColorBrush = Application.Current.Resources[b] as SolidColorBrush;
legacyBrushes.Add(c);
}
this._lvColors.ItemsSource = legacyBrushes;
}
public class SystemColor
{
public string ColorName { get; set; }
public SolidColorBrush ColorBrush { get; set; }
}
public string[] LegacyBrushes = new string[] {
"AppBarBackgroundThemeBrush",
"AppBarBorderThemeBrush",
"AppBarItemBackgroundThemeBrush",
"AppBarItemDisabledForegroundThemeBrush",
"AppBarItemForegroundThemeBrush",
"AppBarItemPointerOverBackgroundThemeBrush",
"AppBarItemPointerOverForegroundThemeBrush",
"AppBarItemPressedForegroundThemeBrush",
"AppBarSeparatorForegroundThemeBrush",
"AppBarToggleButtonCheckedBackgroundThemeBrush",
"AppBarToggleButtonCheckedBorderThemeBrush",
"AppBarToggleButtonCheckedDisabledBackgroundThemeBrush",
"AppBarToggleButtonCheckedDisabledBorderThemeBrush",
"AppBarToggleButtonCheckedDisabledForegroundThemeBrush",
"AppBarToggleButtonCheckedForegroundThemeBrush",
"AppBarToggleButtonCheckedPointerOverBackgroundThemeBrush",
"AppBarToggleButtonCheckedPointerOverBorderThemeBrush",
"AppBarToggleButtonCheckedPressedBackgroundThemeBrush",
"AppBarToggleButtonCheckedPressedBorderThemeBrush",
"AppBarToggleButtonCheckedPressedForegroundThemeBrush",
"AppBarToggleButtonPointerOverBackgroundThemeBrush",
"ApplicationForegroundThemeBrush",
"ApplicationHeaderForegroundThemeBrush",
"ApplicationPageBackgroundThemeBrush",
"ApplicationPointerOverForegroundThemeBrush",
"ApplicationPressedForegroundThemeBrush",
"ApplicationSecondaryForegroundThemeBrush",
"AutoSuggestBackgroundThemeBrush",
"BackButtonBackgroundThemeBrush",
"BackButtonDisabledForegroundThemeBrush",
"BackButtonForegroundThemeBrush",
"BackButtonPointerOverBackgroundThemeBrush",
"BackButtonPointerOverForegroundThemeBrush",
"BackButtonPressedForegroundThemeBrush",
"ButtonBackgroundThemeBrush",
"ButtonBorderThemeBrush",
"ButtonDisabledBackgroundThemeBrush",
"ButtonDisabledBorderThemeBrush",
"ButtonDisabledForegroundThemeBrush",
"ButtonForegroundThemeBrush",
"ButtonPointerOverBackgroundThemeBrush",
"ButtonPointerOverForegroundThemeBrush",
"ButtonPressedBackgroundThemeBrush",
"ButtonPressedForegroundThemeBrush",
"CheckBoxBackgroundThemeBrush",
"CheckBoxBorderThemeBrush",
"CheckBoxContentDisabledForegroundThemeBrush",
"CheckBoxContentForegroundThemeBrush",
"CheckBoxDisabledBackgroundThemeBrush",
"CheckBoxDisabledBorderThemeBrush",
"CheckBoxDisabledForegroundThemeBrush",
"CheckBoxForegroundThemeBrush",
"CheckBoxPointerOverBackgroundThemeBrush",
"CheckBoxPointerOverBorderThemeBrush",
"CheckBoxPointerOverForegroundThemeBrush",
"CheckBoxPressedBackgroundThemeBrush",
"CheckBoxPressedBorderThemeBrush",
"CheckBoxPressedForegroundThemeBrush",
"ComboBoxArrowDisabledForegroundThemeBrush",
"ComboBoxArrowForegroundThemeBrush",
"ComboBoxArrowPressedForegroundThemeBrush",
"ComboBoxBackgroundThemeBrush",
"ComboBoxBorderThemeBrush",
"ComboBoxDisabledBackgroundThemeBrush",
"ComboBoxDisabledBorderThemeBrush",
"ComboBoxDisabledForegroundThemeBrush",
"ComboBoxFocusedBackgroundThemeBrush",
"ComboBoxFocusedBorderThemeBrush",
"ComboBoxFocusedForegroundThemeBrush",
"ComboBoxForegroundThemeBrush",
"ComboBoxHeaderForegroundThemeBrush",
"ComboBoxItemDisabledForegroundThemeBrush",
"ComboBoxItemPointerOverBackgroundThemeBrush",
"ComboBoxItemPointerOverForegroundThemeBrush",
"ComboBoxItemPressedBackgroundThemeBrush",
"ComboBoxItemPressedForegroundThemeBrush",
"ComboBoxItemSelectedBackgroundThemeBrush",
"ComboBoxItemSelectedDisabledBackgroundThemeBrush",
"ComboBoxItemSelectedDisabledForegroundThemeBrush",
"ComboBoxItemSelectedForegroundThemeBrush",
"ComboBoxItemSelectedPointerOverBackgroundThemeBrush",
"ComboBoxPlaceholderTextForegroundThemeBrush",
"ComboBoxPointerOverBackgroundThemeBrush",
"ComboBoxPointerOverBorderThemeBrush",
"ComboBoxPopupBackgroundThemeBrush",
"ComboBoxPopupBorderThemeBrush",
"ComboBoxPopupForegroundThemeBrush",
"ComboBoxPressedBackgroundThemeBrush",
"ComboBoxPressedBorderThemeBrush",
"ComboBoxPressedHighlightThemeBrush",
"ComboBoxPressedForegroundThemeBrush",
"ComboBoxSelectedBackgroundThemeBrush",
"ComboBoxSelectedPointerOverBackgroundThemeBrush",
"ContentDialogBackgroundThemeBrush",
"ContentDialogBorderThemeBrush",
"ContentDialogContentForegroundBrush",
"ContentDialogDimmingThemeBrush",
"DatePickerHeaderForegroundThemeBrush",
"DatePickerForegroundThemeBrush",
"DefaultTextForegroundThemeBrush",
"FlipViewButtonBackgroundThemeBrush",
"FlipViewButtonBorderThemeBrush",
"FlipViewButtonForegroundThemeBrush",
"FlipViewButtonPointerOverBackgroundThemeBrush",
"FlipViewButtonPointerOverBorderThemeBrush",
"FlipViewButtonPointerOverForegroundThemeBrush",
"FlipViewButtonPressedBackgroundThemeBrush",
"FlipViewButtonPressedBorderThemeBrush",
"FlipViewButtonPressedForegroundThemeBrush",
"FlyoutBackgroundThemeBrush",
"FlyoutBorderThemeBrush",
"FocusVisualBlackStrokeThemeBrush",
"FocusVisualWhiteStrokeThemeBrush",
"HyperlinkButtonBackgroundThemeBrush",
"HyperlinkButtonBorderThemeBrush",
"HyperlinkDisabledThemeBrush",
"HyperlinkForegroundThemeBrush",
"HyperlinkPointerOverForegroundThemeBrush",
"HyperlinkPressedForegroundThemeBrush",
"HubSectionHeaderPointerOverForegroundThemeBrush",
"HubSectionHeaderPressedForegroundThemeBrush",
"IMECandidateBackgroundThemeBrush",
"IMECandidateForegroundThemeBrush",
"IMECandidatePointerOverBackgroundThemeBrush",
"IMECandidatePointerOverForegroundThemeBrush",
"IMECandidateSecondaryForegroundThemeBrush",
"IMECandidateSelectedBackgroundThemeBrush",
"IMECandidateSelectedForegroundThemeBrush",
"IMECandidateListBackgroundThemeBrush",
"IMECandidateListPagingButtonBackgroundThemeBrush",
"IMECandidateListPagingButtonBorderThemeBrush",
"IMECandidateListPagingButtonForegroundThemeBrush",
"IMECandidateListPagingButtonPointerOverBackgroundThemeBrush",
"IMECandidateListPagingButtonPointerOverForegroundThemeBrush",
"IMECandidateListPagingButtonPressedBackgroundThemeBrush",
"IMECandidateListPagingButtonPressedForegroundThemeBrush",
"JumpListDefaultEnabledForeground",
"JumpListDefaultEnabledBackground",
"JumpListDefaultDisabledForeground",
"JumpListDefaultDisabledBackground",
"ListBoxBackgroundThemeBrush",
"ListBoxBorderThemeBrush",
"ListBoxDisabledForegroundThemeBrush",
"ListBoxFocusBackgroundThemeBrush",
"ListBoxForegroundThemeBrush",
"ListBoxItemDisabledForegroundThemeBrush",
"ListBoxItemPointerOverBackgroundThemeBrush",
"ListBoxItemPointerOverForegroundThemeBrush",
"ListBoxItemPressedBackgroundThemeBrush",
"ListBoxItemPressedForegroundThemeBrush",
"ListBoxItemSelectedBackgroundThemeBrush",
"ListBoxItemSelectedDisabledBackgroundThemeBrush",
"ListBoxItemSelectedDisabledForegroundThemeBrush",
"ListBoxItemSelectedForegroundThemeBrush",
"ListBoxItemSelectedPointerOverBackgroundThemeBrush",
"ListPickerFlyoutPresenterSelectedItemForegroundThemeBrush",
"ListPickerFlyoutPresenterSelectedItemBackgroundThemeBrush",
"ListViewGroupHeaderForegroundThemeBrush",
"ListViewGroupHeaderPointerOverForegroundThemeBrush",
"ListViewGroupHeaderPressedForegroundThemeBrush",
"ListViewItemCheckHintThemeBrush",
"ListViewItemCheckSelectingThemeBrush",
"ListViewItemCheckThemeBrush",
"ListViewItemDragBackgroundThemeBrush",
"ListViewItemDragForegroundThemeBrush",
"ListViewItemFocusBorderThemeBrush",
"ListViewItemOverlayBackgroundThemeBrush",
"ListViewItemOverlayForegroundThemeBrush",
"ListViewItemOverlaySecondaryForegroundThemeBrush",
"ListViewItemPlaceholderBackgroundThemeBrush",
"ListViewItemPointerOverBackgroundThemeBrush",
"ListViewItemSelectedBackgroundThemeBrush",
"ListViewItemSelectedForegroundThemeBrush",
"ListViewItemSelectedPointerOverBackgroundThemeBrush",
"ListViewItemSelectedPointerOverBorderThemeBrush",
"LoopingSelectorForegroundThemeBrush",
"LoopingSelectorSelectionBackgroundThemeBrush",
"LoopingSelectorSelectionForegroundThemeBrush",
"MediaButtonForegroundThemeBrush",
"MediaButtonBackgroundThemeBrush",
"MediaButtonPointerOverForegroundThemeBrush",
"MediaButtonPointerOverBackgroundThemeBrush",
"MediaButtonPressedForegroundThemeBrush",
"MediaButtonPressedBackgroundThemeBrush",
"MediaButtonPressedBorderThemeBrush",
"MediaControlPanelVideoThemeBrush",
"MediaControlPanelAudioThemeBrush",
"MediaDownloadProgressIndicatorThemeBrush",
"MediaErrorBackgroundThemeBrush",
"MediaTextThemeBrush",
"MenuFlyoutItemFocusedBackgroundThemeBrush",
"MenuFlyoutItemFocusedForegroundThemeBrush",
"MenuFlyoutItemDisabledForegroundThemeBrush",
"MenuFlyoutItemPointerOverBackgroundThemeBrush",
"MenuFlyoutItemPointerOverForegroundThemeBrush",
"MenuFlyoutItemPressedBackgroundThemeBrush",
"MenuFlyoutItemPressedForegroundThemeBrush",
"PivotForegroundThemeBrush",
"PivotHeaderBackgroundSelectedBrush",
"PivotHeaderBackgroundUnselectedBrush",
"PivotHeaderForegroundSelectedBrush",
"PivotHeaderForegroundUnselectedBrush",
"PivotNavButtonBackgroundThemeBrush",
"PivotNavButtonBorderThemeBrush",
"PivotNavButtonForegroundThemeBrush",
"PivotNavButtonPointerOverBackgroundThemeBrush",
"PivotNavButtonPointerOverBorderThemeBrush",
"PivotNavButtonPointerOverForegroundThemeBrush",
"PivotNavButtonPressedBackgroundThemeBrush",
"PivotNavButtonPressedBorderThemeBrush",
"PivotNavButtonPressedForegroundThemeBrush",
"MenuFlyoutSeparatorThemeBrush",
"ProgressBarBackgroundThemeBrush",
"ProgressBarBorderThemeBrush",
"ProgressBarForegroundThemeBrush",
"ProgressBarIndeterminateForegroundThemeBrush",
"RadioButtonBackgroundThemeBrush",
"RadioButtonBorderThemeBrush",
"RadioButtonContentDisabledForegroundThemeBrush",
"RadioButtonContentForegroundThemeBrush",
"RadioButtonDisabledBackgroundThemeBrush",
"RadioButtonDisabledBorderThemeBrush",
"RadioButtonDisabledForegroundThemeBrush",
"RadioButtonForegroundThemeBrush",
"RadioButtonPointerOverBackgroundThemeBrush",
"RadioButtonPointerOverBorderThemeBrush",
"RadioButtonPointerOverForegroundThemeBrush",
"RadioButtonPressedBackgroundThemeBrush",
"RadioButtonPressedBorderThemeBrush",
"RadioButtonPressedForegroundThemeBrush",
"RepeatButtonBorderThemeBrush",
"RepeatButtonDisabledBackgroundThemeBrush",
"RepeatButtonDisabledBorderThemeBrush",
"RepeatButtonDisabledForegroundThemeBrush",
"RepeatButtonForegroundThemeBrush",
"RepeatButtonPointerOverBackgroundThemeBrush",
"RepeatButtonPointerOverForegroundThemeBrush",
"RepeatButtonPressedBackgroundThemeBrush",
"RepeatButtonPressedForegroundThemeBrush",
"ScrollBarButtonForegroundThemeBrush",
"ScrollBarButtonPointerOverBackgroundThemeBrush",
"ScrollBarButtonPointerOverBorderThemeBrush",
"ScrollBarButtonPointerOverForegroundThemeBrush",
"ScrollBarButtonPressedBackgroundThemeBrush",
"ScrollBarButtonPressedBorderThemeBrush",
"ScrollBarButtonPressedForegroundThemeBrush",
"ScrollBarPanningBackgroundThemeBrush",
"ScrollBarPanningBorderThemeBrush",
"ScrollBarThumbBackgroundThemeBrush",
"ScrollBarThumbBorderThemeBrush",
"ScrollBarThumbPointerOverBackgroundThemeBrush",
"ScrollBarThumbPointerOverBorderThemeBrush",
"ScrollBarThumbPressedBackgroundThemeBrush",
"ScrollBarThumbPressedBorderThemeBrush",
"ScrollBarTrackBackgroundThemeBrush",
"ScrollBarTrackBorderThemeBrush",
"SearchBoxBackgroundThemeBrush",
"SearchBoxBorderThemeBrush",
"SearchBoxDisabledBackgroundThemeBrush",
"SearchBoxDisabledTextThemeBrush",
"SearchBoxDisabledBorderThemeBrush",
"SearchBoxPointerOverBackgroundThemeBrush",
"SearchBoxPointerOverTextThemeBrush",
"SearchBoxPointerOverBorderThemeBrush",
"SearchBoxFocusedBackgroundThemeBrush",
"SearchBoxFocusedTextThemeBrush",
"SearchBoxFocusedBorderThemeBrush",
"SearchBoxButtonBackgroundThemeBrush",
"SearchBoxButtonForegroundThemeBrush",
"SearchBoxButtonPointerOverForegroundThemeBrush",
"SearchBoxButtonPointerOverBackgroundThemeBrush",
"SearchBoxSeparatorSuggestionForegroundThemeBrush",
"SearchBoxHitHighlightForegroundThemeBrush",
"SearchBoxHitHighlightSelectedForegroundThemeBrush",
"SearchBoxIMECandidateListSeparatorThemeBrush",
"SearchBoxForegroundThemeBrush",
"SemanticZoomButtonBackgroundThemeBrush",
"SemanticZoomButtonBorderThemeBrush",
"SemanticZoomButtonForegroundThemeBrush",
"SemanticZoomButtonPointerOverBackgroundThemeBrush",
"SemanticZoomButtonPointerOverBorderThemeBrush",
"SemanticZoomButtonPointerOverForegroundThemeBrush",
"SemanticZoomButtonPressedBackgroundThemeBrush",
"SemanticZoomButtonPressedBorderThemeBrush",
"SemanticZoomButtonPressedForegroundThemeBrush",
"SettingsFlyoutBackgroundThemeBrush",
"SettingsFlyoutBackButtonPointerOverBackgroundThemeBrush",
"SettingsFlyoutHeaderBackgroundThemeBrush",
"SettingsFlyoutHeaderForegroundThemeBrush",
"SliderBorderThemeBrush",
"SliderDisabledBorderThemeBrush",
"SliderThumbBackgroundThemeBrush",
"SliderThumbBorderThemeBrush",
"SliderThumbDisabledBackgroundThemeBrush",
"SliderThumbPointerOverBackgroundThemeBrush",
"SliderThumbPointerOverBorderThemeBrush",
"SliderThumbPressedBackgroundThemeBrush",
"SliderThumbPressedBorderThemeBrush",
"SliderTickMarkInlineBackgroundThemeBrush",
"SliderTickMarkInlineDisabledForegroundThemeBrush",
"SliderTickmarkOutsideBackgroundThemeBrush",
"SliderTickMarkOutsideDisabledForegroundThemeBrush",
"SliderTrackBackgroundThemeBrush",
"SliderTrackDecreaseBackgroundThemeBrush",
"SliderTrackDecreaseDisabledBackgroundThemeBrush",
"SliderTrackDecreasePointerOverBackgroundThemeBrush",
"SliderTrackDecreasePressedBackgroundThemeBrush",
"SliderTrackDisabledBackgroundThemeBrush",
"SliderTrackPointerOverBackgroundThemeBrush",
"SliderTrackPressedBackgroundThemeBrush",
"SliderHeaderForegroundThemeBrush",
"TextBoxForegroundHeaderThemeBrush",
"TextBoxPlaceholderTextThemeBrush",
"TextBoxBackgroundThemeBrush",
"TextSelectionHighlightColorThemeBrush",
"TextBoxBorderThemeBrush",
"TextBoxButtonBackgroundThemeBrush",
"TextBoxButtonBorderThemeBrush",
"TextBoxButtonForegroundThemeBrush",
"TextBoxButtonPointerOverBackgroundThemeBrush",
"TextBoxButtonPointerOverBorderThemeBrush",
"TextBoxButtonPointerOverForegroundThemeBrush",
"TextBoxButtonPressedBackgroundThemeBrush",
"TextBoxButtonPressedBorderThemeBrush",
"TextBoxButtonPressedForegroundThemeBrush",
"TextBoxDisabledBackgroundThemeBrush",
"TextBoxDisabledBorderThemeBrush",
"TextBoxDisabledForegroundThemeBrush",
"TextBoxForegroundThemeBrush",
"ThumbBackgroundThemeBrush",
"ThumbBorderThemeBrush",
"ThumbPointerOverBackgroundThemeBrush",
"ThumbPointerOverBorderThemeBrush",
"ThumbPressedBackgroundThemeBrush",
"ThumbPressedBorderThemeBrush",
"TimePickerHeaderForegroundThemeBrush",
"TimePickerForegroundThemeBrush",
"ToggleButtonBackgroundThemeBrush",
"ToggleButtonBorderThemeBrush",
"ToggleButtonCheckedBackgroundThemeBrush",
"ToggleButtonCheckedBorderThemeBrush",
"ToggleButtonCheckedDisabledBackgroundThemeBrush",
"ToggleButtonCheckedDisabledForegroundThemeBrush",
"ToggleButtonCheckedForegroundThemeBrush",
"ToggleButtonCheckedPointerOverBackgroundThemeBrush",
"ToggleButtonCheckedPointerOverBorderThemeBrush",
"ToggleButtonCheckedPressedBackgroundThemeBrush",
"ToggleButtonCheckedPressedBorderThemeBrush",
"ToggleButtonCheckedPressedForegroundThemeBrush",
"ToggleButtonDisabledBorderThemeBrush",
"ToggleButtonDisabledForegroundThemeBrush",
"ToggleButtonForegroundThemeBrush",
"ToggleButtonPointerOverBackgroundThemeBrush",
"ToggleButtonPressedBackgroundThemeBrush",
"ToggleButtonPressedForegroundThemeBrush",
"ToggleSwitchCurtainBackgroundThemeBrush",
"ToggleSwitchCurtainDisabledBackgroundThemeBrush",
"ToggleSwitchCurtainPointerOverBackgroundThemeBrush",
"ToggleSwitchCurtainPressedBackgroundThemeBrush",
"ToggleSwitchDisabledForegroundThemeBrush",
"ToggleSwitchForegroundThemeBrush",
"ToggleSwitchHeaderDisabledForegroundThemeBrush",
"ToggleSwitchHeaderForegroundThemeBrush",
"ToggleSwitchOuterBorderBorderThemeBrush",
"ToggleSwitchOuterBorderDisabledBorderThemeBrush",
"ToggleSwitchThumbBackgroundThemeBrush",
"ToggleSwitchThumbBorderThemeBrush",
"ToggleSwitchThumbDisabledBackgroundThemeBrush",
"ToggleSwitchThumbDisabledBorderThemeBrush",
"ToggleSwitchThumbPointerOverBackgroundThemeBrush",
"ToggleSwitchThumbPointerOverBorderThemeBrush",
"ToggleSwitchThumbPressedBackgroundThemeBrush",
"ToggleSwitchThumbPressedForegroundThemeBrush",
"ToggleSwitchTrackBackgroundThemeBrush",
"ToggleSwitchTrackBorderThemeBrush",
"ToggleSwitchTrackDisabledBackgroundThemeBrush",
"ToggleSwitchTrackPointerOverBackgroundThemeBrush",
"ToggleSwitchTrackPressedBackgroundThemeBrush",
"ToolTipBackgroundThemeBrush",
"ToolTipBorderThemeBrush",
"ToolTipForegroundThemeBrush",
};
public string[] SystemBrushes = new string[] {
"SystemControlBackgroundAccentBrush",
"SystemControlBackgroundAltHighBrush",
"SystemControlBackgroundAltMediumHighBrush",
"SystemControlBackgroundAltMediumLowBrush",
"SystemControlBackgroundBaseHighBrush",
"SystemControlBackgroundBaseLowBrush",
"SystemControlBackgroundBaseMediumBrush",
"SystemControlBackgroundBaseMediumHighBrush",
"SystemControlBackgroundBaseMediumLowBrush",
"SystemControlBackgroundChromeBlackHighBrush",
"SystemControlBackgroundChromeBlackMediumBrush",
"SystemControlBackgroundChromeMediumBrush",
"SystemControlBackgroundChromeMediumLowBrush",
"SystemControlBackgroundChromeWhiteBrush",
"SystemControlBackgroundListLowBrush",
"SystemControlBackgroundListMediumBrush",
"SystemControlDisabledAccentBrush",
"SystemControlDisabledBaseHighBrush",
"SystemControlDisabledBaseLowBrush",
"SystemControlDisabledBaseMediumLowBrush",
"SystemControlDisabledChromeDisabledHighBrush",
"SystemControlDisabledChromeDisabledLowBrush",
"SystemControlDisabledChromeHighBrush",
"SystemControlDisabledChromeMediumLowBrush",
"SystemControlDisabledListMediumBrush",
"SystemControlDisabledTransparentBrush",
"SystemControlForegroundAccentBrush",
"SystemControlForegroundAltHighBrush",
"SystemControlForegroundAltMediumHighBrush",
"SystemControlForegroundBaseHighBrush",
"SystemControlForegroundBaseLowBrush",
"SystemControlForegroundBaseMediumBrush",
"SystemControlForegroundBaseMediumHighBrush",
"SystemControlForegroundBaseMediumLowBrush",
"SystemControlForegroundChromeBlackHighBrush",
"SystemControlForegroundChromeHighBrush",
"SystemControlForegroundChromeMediumBrush",
"SystemControlForegroundChromeWhiteBrush",
"SystemControlForegroundChromeDisabledLowBrush",
"SystemControlForegroundListLowBrush",
"SystemControlForegroundListMediumBrush",
"SystemControlForegroundTransparentBrush",
"SystemControlForegroundChromeBlackMediumBrush",
"SystemControlForegroundChromeBlackMediumLowBrush",
"SystemControlHighlightAccentBrush",
"SystemControlHighlightAltAccentBrush",
"SystemControlHighlightAltAltHighBrush",
"SystemControlHighlightAltBaseHighBrush",
"SystemControlHighlightAltBaseLowBrush",
"SystemControlHighlightAltBaseMediumBrush",
"SystemControlHighlightAltBaseMediumHighBrush",
"SystemControlHighlightAltAltMediumHighBrush",
"SystemControlHighlightAltBaseMediumLowBrush",
"SystemControlHighlightAltListAccentHighBrush",
"SystemControlHighlightAltListAccentLowBrush",
"SystemControlHighlightAltListAccentMediumBrush",
"SystemControlHighlightAltChromeWhiteBrush",
"SystemControlHighlightAltTransparentBrush",
"SystemControlHighlightBaseHighBrush",
"SystemControlHighlightBaseLowBrush",
"SystemControlHighlightBaseMediumBrush",
"SystemControlHighlightBaseMediumHighBrush",
"SystemControlHighlightBaseMediumLowBrush",
"SystemControlHighlightChromeAltLowBrush",
"SystemControlHighlightChromeHighBrush",
"SystemControlHighlightListAccentHighBrush",
"SystemControlHighlightListAccentLowBrush",
"SystemControlHighlightListAccentMediumBrush",
"SystemControlHighlightListMediumBrush",
"SystemControlHighlightListLowBrush",
"SystemControlHighlightTransparentBrush",
"SystemControlHyperlinkTextBrush",
"SystemControlHyperlinkBaseHighBrush",
"SystemControlHyperlinkBaseMediumBrush",
"SystemControlHyperlinkBaseMediumHighBrush",
"SystemControlPageBackgroundAltMediumBrush",
"SystemControlPageBackgroundMediumAltMediumBrush",
"SystemControlPageBackgroundBaseLowBrush",
"SystemControlPageBackgroundBaseMediumBrush",
"SystemControlPageBackgroundListLowBrush",
"SystemControlPageBackgroundChromeLowBrush",
"SystemControlPageTextBaseHighBrush",
"SystemControlPageTextBaseMediumBrush",
"SystemControlPageTextChromeBlackMediumLowBrush",
};
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox cb = sender as CheckBox;
Frame rootFrame = Window.Current.Content as Frame;
rootFrame.RequestedTheme = cb.IsChecked.Value ? ElementTheme.Dark : ElementTheme.Light;
}
<ListView Name="_lvColors" SelectionMode="None" Margin="0 30 0 0">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Height="48">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ColorName}" VerticalAlignment="Center" IsTextSelectionEnabled="True" Margin="10 0"/>
<Grid Background="{Binding ColorBrush}" Grid.Column="1"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Padding" Value="0" />
<Setter Property="Margin" Value="0" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
<CheckBox Content="Theme" Checked="CheckBox_Checked" Unchecked="CheckBox_Checked" HorizontalAlignment="Center" VerticalAlignment="Top"/>

Reach a TextBlock from a specific ListViewItem from the ListView in Windows Phone 8.1 XAML programmatically

I am a new developer on Windows Phone 8.1, I am try to reach a specific ListView item from the ListView collection and be able to color it or color the TextBock inside of it, But I can't reach the item or reach any of items inside of ListView, Please take a look for my below code :
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
SQLiteRT db1 = new SQLiteRT();
var db_connection = await db1.Connection("MyDB.sqlite");
List<MyTBL> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;");
db_connection.Close();
LV_Options.ItemsSource = t_list;
}
// my List View called LV_Options
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListView lv1 = sender as ListView;
if (lv1 == null)
return;
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
tb.FontSize = 17; // here I got debug error (it not worked !!!!!!!)
var item = LV_Options.Items.ElementAt(3); // this seems not work also !!!!
item.BackColor = Color.LightSteelBlue;
}
As you can see above, I tried to reach a specific item by LV_Options.Items.ElementAt(3) but it doesn't work! I also tried to reach the TextBlock from the selected List view item, but also not worked !
(Updated)
XAML code :
<!-- Title Panel -->
<StackPanel Grid.Row="0" Margin="19,0,0,0">
<TextBlock Name="TB_Rslt" Text="Here result of your answer" Style="{ThemeResource TitleTextBlockStyle}" Margin="0,12,0,0"/>
<TextBlock Text="page title" Margin="0,-6.5,0,26.5" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
</StackPanel>
<!--TODO: Content should be placed within the following grid-->
<Grid Grid.Row="1" x:Name="ContentRoot" Margin="19,10,19,15">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Name="TB_Question" Text="Choose Answer " Margin="0,0,25,0" HorizontalAlignment="Right" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" />
<TextBlock Name="TB_EnWord" Text="" Margin="90,0,15,0" HorizontalAlignment="Left" FontWeight="Bold" FontSize="22" FontFamily="Verdana" RenderTransformOrigin="0.5,0.5" TextAlignment="Right" />
<StackPanel Grid.Row="1" Margin="5,22,0,0">
<ListView Name="LV_Options" SelectionChanged="LV_Options_SelectionChanged">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding AMean1}" TextWrapping="Wrap"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
<Button Name="Btn_Answer" Content="Ansewr" HorizontalAlignment="Left" Grid.Row="1" VerticalAlignment="Bottom" Click="Btn_Answer_Click"/>
My application is a quiz application that offer 4 choices/options as answers for each question, and when user select a true answer, I want to highlight the true answer(true choice) by make its background to green, and if the user selected wrong answer/option I want to make the background of that answer (a specific List View item) with red.
Any help please ?
You're not going to be able to access an element inside a data template like that. Instead, leverage the binding to a view model to set the color and other view-related properties. First, create a wrapper view model for your data class:
public class MyTBLViewModel : INotifyPropertyChanged
{
public MyTBL Entity
{
get { return _entity; }
}
private readonly MyTBL _entity;
public Brush Highlight
{
get { return _brush; }
set
{
_brush = value;
RaisePropertyChanged("Highlight");
}
}
private Brush _highlight;
public double ItemFontSize
{
get { return _itemFontSize; }
set
{
_itemFontSize = value;
RaisePropertyChanged("ItemFontSize");
}
}
private Brush _itemFontSize;
public MyTBLViewModel(MyTBL entity)
{
_entity = entity;
_highlight = new SolidColorBrush(Colors.Transparent);
_itemFontSize = 12;
}
public event PropertyChangedEventArgs PropertyChanged;
protected void RaisePropertyChanged(string propName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propName));
}
}
Use this as your ItemsSource:
List<MyTBLViewModel> t_list = db1.GetTable("SELECT * FROM MyTBL LIMIT 4 ORDER BY RANDOM() ;")
.AsEnumerable().Select(entity => new MyTBLViewModel(entity)).ToList();
Now in your view, bind the view elements to "Highlight" and "ItemFontSize", and to any other properties you like:
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6" Background="{Binding Highlight}">
<StackPanel VerticalAlignment="Top" Margin="10,0,0,0">
<TextBlock Name="TB_AMean1" Text="{Binding Entity.AMean1}" TextWrapping="Wrap"
FontSize="{Binding ItemFontSize}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
Finally, you can get the data item from the SelectionChangedEventArgs -- use it to update your view-related properties:
private void LV_Options_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.AddedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Color.LightSteelBlue);
item.ItemFontSize = 17;
}
foreach (var item in e.RemovedItems.OfType<MyTBLViewModel>())
{
item.Highlight = new SolidColorBrush(Colors.Transparent);
item.ItemFontSize = 12;
}
}
var item = LV_Options.Items.ElementAt(3);
This line is incorrect. It will not return you a TextBlock. I don't know what a .BackColor is, and it should not compile. The Items property in a ListView will return you a list of ListViewItems. If you want to access the inside element from a ListViewItem, you'll need to access the ContentTemplateRoot property.
Do not use var ever. It lets you assume that you know the type, whereas if you explicitly typed the declaration you would realize you're doing it wrong.
MyTBL wrd = lv1.SelectedItem as MyTBL;
if (wrd == null)
return;
TextBlock tb = lv1.FindName("TB_AMean1") as TextBlock;
What is a MyTBL type? FindName is only available to framework DependencyObjects so I'm assuming it's a user control? You have to provide a lot more code to show us what you're doing and what you're setting the ListView's ItemsSource and ItemTemplate with and what these errors are and how you have 2 breaking debug errors at once and what the error messages are.
Comprehending runtime error messages is a huge part of being a good developer.

How to Display Gridview items with variable width in Windows 8?

My GridView items having the size of it's first item size. How do i can change this behaviour ?
How to display GridView items with variable Width as per the content ?
I want to show the first one but i am getting second one. Any suggestion to do that?
Check Windows 8 GridView and Variable-Sized Items and Different Sized Tile Items in WinRT GridView and also check Variable Sized Grid Template Hope this help
You can create such view of GridView by setting ItemsPanel to WrapPanel, you can get WrapPanel on Jerry Nixon's blog. Here's the code.
XAML
<GridView x:Name="gv">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<local:WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate>
<Grid Height="140" Width="{Binding MyWidth}">
<Grid.Background>
<SolidColorBrush Color="{Binding MyColor}" />
</Grid.Background>
<TextBlock FontSize="20" VerticalAlignment="Bottom" Margin="10,0,0,10">
<Run Text="{Binding MyWidth}" />
</TextBlock>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
C#
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var list = new List<ViewModel>()
{
new ViewModel(110, Colors.LawnGreen),
new ViewModel(50, Colors.DarkBlue),
new ViewModel(130, Colors.Firebrick),
new ViewModel(60, Colors.RosyBrown),
new ViewModel(100, Colors.IndianRed),
new ViewModel(210, Colors.BurlyWood),
new ViewModel(150, Colors.Turquoise)
};
gv.ItemsSource = list;
}
public class ViewModel
{
public double MyWidth { get; set; }
public Color MyColor { get; set; }
public ViewModel(double _MyWidth, Color _MyColor)
{
MyWidth = _MyWidth;
MyColor = _MyColor;
}
}
Here is my solution.
//variable sized grid view
public class VariableSizedGridView : GridView
{
protected override void PrepareContainerForItemOverride(Windows.UI.Xaml.DependencyObject element, object item)
{
try
{
dynamic gridItem = item;
var typeItem = item as CommonType;
if (typeItem != null)
{
var heightPecentage = (300.0 / typeItem.WbmImage.PixelHeight);
var itemWidth = typeItem.WbmImage.PixelWidth * heightPecentage;
var columnSpan = Convert.ToInt32(itemWidth / 10.0);
if (gridItem != null)
{
element.SetValue(VariableSizedWrapGrid.ItemWidthProperty, itemWidth);
element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, columnSpan);
element.SetValue(VariableSizedWrapGrid.RowSpanProperty, 1);
}
}
}
catch
{
element.SetValue(VariableSizedWrapGrid.ItemWidthProperty, 100);
element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, 1);
element.SetValue(VariableSizedWrapGrid.RowSpanProperty, 1);
}
finally
{
base.PrepareContainerForItemOverride(element, item);
}
}
//Collection View source
<CollectionViewSource x:Name="collectionViewSource"
Source="{Binding ImageList,Mode=TwoWay}"
IsSourceGrouped="False"
ItemsPath="Items" />
//variable sized Grid view xaml
<controls:VariableSizedGridView x:Name="ImageGridView"
AutomationProperties.AutomationId="ImageGridView"
ItemsSource="{Binding Source={StaticResource collectionViewSource}}"
IsItemClickEnabled="True"
TabIndex="1" >
<controls:VariableSizedGridView.ItemTemplate>
<DataTemplate>
<Grid Height="300" >
<Image Stretch="Uniform" Source="{Binding WbmImage}" />
</Grid>
</DataTemplate>
</controls:VariableSizedGridView.ItemTemplate>
<controls:VariableSizedGridView.ItemsPanel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid ItemWidth="10" ItemHeight="300" Orientation="Vertical"/>
</ItemsPanelTemplate>
</controls:VariableSizedGridView.ItemsPanel>
</controls:VariableSizedGridView>

Categories