I need to change the color of a rectangle in a GridView when the item is selected.
Unselected item
Selected item
My Main Page in XAML.
<Page
x:Class="GridViewWithSelectedItem.Views.MainPage"
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:views="using:GridViewWithSelectedItem.Views"
Style="{StaticResource PageStyle}"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="TileTemplate" x:DataType="views:Article">
<Border BorderThickness="2,2,2,2" BorderBrush="#FF868484" Margin="3,3,3,3" HorizontalAlignment="Stretch" MaxWidth="600" MinWidth="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="60"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Rectangle Fill="Black" Grid.RowSpan="3"/>
<StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="1">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Number}"/>
<TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Title}" FontWeight="Bold"/>
</StackPanel>
<TextBlock Grid.Row="1" Grid.Column="1" FontSize="20" Text="{x:Bind Description}" TextWrapping="WrapWholeWords"/>
<StackPanel Background="LightBlue" Padding="5,0,0,0" Grid.Row="2" Grid.Column="1">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
<TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Date}" FontWeight="Bold"/>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</Page.Resources>
<Grid x:Name="ContentArea" Margin="{StaticResource MediumLeftRightMargin}">
<Grid Background="White" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="0,25,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="600"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="800"/>
</Grid.RowDefinitions>
<TextBlock Text="The Guardian" FontSize="35" FontWeight="Bold" Grid.ColumnSpan="2" HorizontalAlignment="Center"/>
<GridView
BorderThickness="2,2,0,2" BorderBrush="#FF868484"
MinWidth="600"
Grid.Column="0"
Grid.Row="1"
Padding="5,5,5,5"
HorizontalAlignment="Center"
CanDragItems="False"
IsItemClickEnabled="true"
IsTapEnabled="False"
IsSwipeEnabled="False"
ItemsSource="{x:Bind Articles}"
ItemTemplate="{StaticResource TileTemplate}"
SelectedItem="{x:Bind Mode=TwoWay, Path=SelectedArticle}"
/>
<RelativePanel Grid.Row="1" Grid.Column="1" Background="WhiteSmoke" BorderThickness="2" BorderBrush="#FF868484" Padding="10">
<Grid RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
<Grid VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap" Foreground="DarkBlue" FontWeight="Bold" Text="{x:Bind Path=SelectedArticle.Number, Mode=OneWay}"/>
<TextBlock FontSize="20" TextWrapping="Wrap" Foreground="DarkBlue" Text="{x:Bind Path=SelectedArticle.Title, Mode=OneWay}" FontWeight="Bold"/>
</StackPanel>
<TextBlock Grid.Row="1" FontSize="20" Text="{x:Bind Path=SelectedArticle.Description, Mode=OneWay}" TextWrapping="WrapWholeWords"/>
</Grid>
</Grid>
<RelativePanel Background="LightBlue" Padding="5,0,0,0" RelativePanel.AlignBottomWithPanel="True" RelativePanel.AlignLeftWithPanel="True" RelativePanel.AlignRightWithPanel="True">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="20" Margin="0,0,5,0" TextWrapping="Wrap">Date :</TextBlock>
<TextBlock Foreground="Red" FontSize="20" TextWrapping="Wrap" Text="{x:Bind Path=SelectedArticle.Date, Mode=OneWay}" FontWeight="Bold"/>
</StackPanel>
</RelativePanel>
</RelativePanel>
</Grid>
</Grid>
</Page>
And the class of my XAML Page.
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.UI.Xaml.Controls;
namespace GridViewWithSelectedItem.Views
{
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public ObservableCollection<Article> Articles;
private Article _selectedArticle;
public Article SelectedArticle
{
get { return _selectedArticle; }
set { Set(ref _selectedArticle, value); }
}
public MainPage()
{
InitializeComponent();
Articles = new ObservableCollection<Article>();
Articles.Add(new Article(0, "Uighurs", "Being young' leads to detention in China's Xinjiang region", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(1, "Brexit", "Chances of Brexit deal hang on Boris Johnson and Ursula von der Leyen dinner", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(2, "Environment", "Secretive ‘gold rush’ for deep-sea mining dominated by handful of firms", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(3, "Juukan Gerge induiry", "Juukan Gorge inquiry: Rio Tinto's decision to blow up Indigenous rock shelters 'inexcusable'", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(4, "Australia", "British journalist uncovered Australian woman's alleged plan to kill parents on dark web, police say", DateTime.Parse("09/12/2020")));
Articles.Add(new Article(5, "Coronavirus", "Nine out of 10 in poor nations to miss out on inoculation as west buys up Covid vaccines", DateTime.Parse("09/12/2020")));
}
public event PropertyChangedEventHandler PropertyChanged;
private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public class Article
{
public int Number { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public Article(int number, string title, string description, DateTime date)
{
Number = number;
Title = title;
Description = description;
Date = Date;
}
}
}
I see AutomationProperty.name can help me but i don't understand how to use it.
I found a way to change the color of a selected item in my class but i need to recreate the collection and i cost lot of resources. I think its possible to make it in XAML code.
Edit: I made a simple exemple of my code.
OneDrive link
You could add a Brush property into the Article class, and bind the Brush property to Rectangle.Fill property of your DataTemplate to change the color when an item of GridView control is selected.
Please check the following code:
In DataTemplate of your xaml file:
<Rectangle x:Name="rectangle" Fill="{x:Bind Brush}" Grid.RowSpan="3"/>
……
<GridView …… SelectionChanged="GridView_SelectionChanged" />
In code-behind:
public class Article
{
……
public SolidColorBrush Brush { get; set; }
public Article(int number, string title, string description, DateTime date)
{
……
Brush = new SolidColorBrush(Colors.Black);
}
}
Add a _preSelectedArticle property to save the previous item in MainPage class:
private Article _preSelectedArticle;
Change the value of Brush property of selected item and previous selected item:
private void GridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(_preSelectedArticle==null)
{
SelectedArticle.Brush.Color = Colors.Green;
_preSelectedArticle = SelectedArticle;
}
if (_preSelectedArticle!=null&&_preSelectedArticle!= SelectedArticle)
{
_preSelectedArticle.Brush.Color = Colors.Black;
SelectedArticle.Brush.Color = Colors.Green;
_preSelectedArticle = SelectedArticle;
}
}
Related
What I want to do is to be able to access an object's properties through a bound textblock that is found in a viewModel class. So say I want to access the OrderID of the Orders class in a bound textblock that is stored in a viewModel class.
What I have for that is:
<textblock text="{Binding Path=Order.OrderID}"/>
This is connected to the order's orderID as when I change the OrderID in the ViewModel class the change is reflected in the textblock. The problem occurs when I try to load the OrderID from another class.
The Other class:
public class ModifyOrder
{
private ViewModel boundData;
public ModifyOrder()
{
boundData = new ViewModel();
}
public void ChangeOrderID()
{
boundData.Order.OrderID = 10;
}
}
The changes here don't get transfered to the static _Order in the ViewModel class.
This is the viewModel class:
public class ViewModel : INotifyPropertyChanged
{
private Orders _Order;
public Orders Order
{
get { return _Order; }
set
{
if (_Order != value)
{
_Order = value;
}
}
}
public ViewModel()
{
Order = new Orders();
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
I have the ViewModel class loaded into the UI's DataContext and my other bound variables in the ViewModel class work fine but for some reason either the bound textblock isn't accessing the Order.OrderID (Which I don't think is the problem since I can modify the Order.OrderID in the ViewModel class and the changes are reflected) OR the class that's modifying my Order isn't able to modify the OrderID.
I've already tried to load a new Order class with the new OrderID and then try to load the ViewModel's _Order with the ModifyOrder's new Order but that hasn't worked out either.
This is the Orders class:
public class Orders : INotifyPropertyChanged
{
private int _OrderID;
public int OrderID
{
get { return _OrderID; }
set
{
if(_OrderID != value)
{
_OrderID = Value
OnPropertyChanged(nameof(OrderID));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
<Page x:Class="SPWally.FunctionalPages.LookupOrders"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:SPWally.FunctionalPages"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
Title="LookupOrders">
<Grid Background="AliceBlue">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="20"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Text="Search For Order" />
<TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,335,0" Text="OrderID: " />
<TextBox Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Width="300" Margin="0,0,20,0" Text="{Binding Path=OrderIDSearch, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Width="40" Height="20" Margin="10,0,0,0" Content="Find" Click="Find_Click" />
<Button Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Width="50" Height="20" Margin="70,0,0,0" Content="Refund" Click="Refund_Click" />
<TextBlock Grid.Row="3" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="OrderID:"/>
<TextBlock Grid.Row="4" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Customer:"/>
<TextBlock Grid.Row="5" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Product:"/>
<TextBlock Grid.Row="6" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Branch:"/>
<TextBlock Grid.Row="7" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Sales Price:"/>
<TextBlock Grid.Row="8" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,100,0" Text="Quantity:"/>
<TextBlock Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.OrderID, Mode=TwoWay}"/>
<TextBlock Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Customer.FullName, Mode=TwoWay}"/>
<TextBlock Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Product.ProductName, Mode=TwoWay}"/>
<TextBlock Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Branch.BranchName, Mode=TwoWay}"/>
<TextBlock Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.SalesPrice, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="8" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Margin="30,0,0,0" Text="{Binding Path=Order.Stocks, Mode=TwoWay}"/>
<Button Grid.Row="10" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="60" Height="25" Content="Cancel" Command="{x:Static NavigationCommands.BrowseBack}" />
</Grid>
</Page>
Keep in mind that I've literally learned everything I know about data binding in the last 48 hours so bear with me here.
Any kind of help at all is very much appreciated. Thank!
You need to implement INotifyPropertyChanged in Orders class.
You need to Invoke OnPropertyChanged() inside all setters.
Where your view model is getting instantiated ? I guess since you are recreating your viewmodel instance in ModifyOrder class
boundData = new ViewModel();
binding is lost and may be because of that its not showing up .
...Yeah, so. It was the
public ViewModel()
{
Order = new Order();
}
that was wiping clean the private static Orders _Order in the ViewModel class every time it was instantiated so I changed it to
public ViewModel()
{
if (_Order == null)
{
Order = new Order();
}
}
and that fixed the problem...
Thanks to everyone that helped me out with this! I learned a lot from you all!
I'm going to go cry myself to sleep now <3
I'm writing my first program with the use wpf and mvvm.
Have a problem, that in the case of changes data in fields of selecteditem, selecting a new item becomes impossible.
If add to listview attribute SelectionMode="Single", then if many times try pick item, exeption:
The element with the same key has already been added.
image: https://www.dropbox.com/s/ey7izl19803uuhc/1.png
If this attribute is removed, then pick another item, simply does not occur.
Image: https://dl.dropboxusercontent.com/u/32438899/2.png
If the data has not changed, the navigation works fine.
XAML code:
<?xml version="1.0" encoding="utf-8" ?>
<Window x:Class="MHConfigurator.Views.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DataContext="{Binding Path=MainViewModel}"
Title="Редактирование шаблонов писем" Height="Auto" Width="1000" MinWidth="1000" MinHeight="400">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" Margin="7">
<TextBlock DockPanel.Dock="Left" Margin="5,5,2,5" HorizontalAlignment="Left">Поиск:</TextBlock>
<TextBox DockPanel.Dock="Right" Margin="2,2,2,2" HorizontalAlignment="Stretch" Text="{Binding SearchString, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</DockPanel>
<ListView Grid.Row="1" ItemsSource="{Binding Path=MailProperties, Mode=TwoWay}" Width="Auto" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Margin="5" SelectedItem="{Binding Path=CurrentProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding ButtonID, Mode=TwoWay}" Header="ID шаблона" Width="Auto" />
<GridViewColumn DisplayMemberBinding="{Binding Description, Mode=TwoWay}" Header="Описание" Width="Auto" />
</GridView>
</ListView.View>
</ListView>
<Grid VerticalAlignment="Center" Grid.Row="2" DataContext="{Binding CurrentProperty}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" Grid.Column="0">
<TextBlock DockPanel.Dock="Left" Margin="5,5,2,5" VerticalAlignment="Center" HorizontalAlignment="Left">ID шаблона:</TextBlock>
<TextBox DockPanel.Dock="Right" Margin="2,2,2,2" VerticalAlignment="Center" HorizontalAlignment="Stretch"
VerticalContentAlignment="Center" Text="{Binding ButtonID}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="1" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillSubject}">Заполнять тему</CheckBox>
</DockPanel>
<DockPanel Grid.Row="2" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillTO}">Заполнять адресатов</CheckBox>
</DockPanel>
<DockPanel Grid.Row="3" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillCopy}">Заполнять копию</CheckBox>
</DockPanel>
<DockPanel Grid.Row="4" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding FillHideCopy}">Заполнять скрытую копию</CheckBox>
</DockPanel>
<DockPanel Grid.Row="5" Grid.Column="0">
<CheckBox DockPanel.Dock="Left" HorizontalAlignment="Left" Margin="5" VerticalAlignment="Center" IsChecked="{Binding HighImportance}">Высокая важность</CheckBox>
</DockPanel>
<DockPanel Grid.Row="0" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115" >Описание шаблона:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding Description}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="1" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Тема письма:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding Subject}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="2" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Адресаты:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding TO}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="3" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Копия:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding Copy}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="4" Grid.Column="1">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="10,5,2,5" Width="115">Скрытая копия:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" TextWrapping="Wrap" VerticalContentAlignment="Center" Text="{Binding HideCopy}"></TextBox>
</DockPanel>
<DockPanel Grid.Row="5" Grid.Column="1">
<CheckBox DockPanel.Dock="Left" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5">Напоминание</CheckBox>
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center" Margin="4">Время напоминания:</TextBlock>
<TextBox DockPanel.Dock="Left" Margin="2,2,5,2" VerticalContentAlignment="Center"></TextBox>
</DockPanel>
<DockPanel Grid.Row="6" Grid.Column="1">
<CheckBox DockPanel.Dock="Left" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5">Заполнять текст письма</CheckBox>
</DockPanel>
<DockPanel Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="2">
<Button DockPanel.Dock="Left" Margin="15" HorizontalAlignment="Left" VerticalAlignment="Center" Width="150" Height="40">Добавить новый шаблон</Button>
<Button DockPanel.Dock="Left" Margin="15" HorizontalAlignment="Left" VerticalAlignment="Center" Width="150" Height="40">Сохранить</Button>
<Button DockPanel.Dock="Left" Margin="15" HorizontalAlignment="Left" VerticalAlignment="Center" Width="150" Height="40">Отмена</Button>
<TextBlock DockPanel.Dock="Left" Margin="0,4,4,4" VerticalAlignment="Center">Заметка:</TextBlock>
<TextBox DockPanel.Dock="Right" Margin="5" TextWrapping="Wrap" AcceptsReturn="True" Height="70" HorizontalAlignment="Stretch" VerticalScrollBarVisibility="Visible"
SpellCheck.IsEnabled="True" Language="ru-ru"></TextBox>
</DockPanel>
</Grid>
</Grid>
</Window>
In viewmodel problems can not be. It is very easy, PropertyChanged called whenever necessary.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MugenMvvmToolkit;
using MugenMvvmToolkit.ViewModels;
using MugenMvvmToolkit.Models;
using System.Windows.Input;
using MHConfigurator.Models;
using System.Windows;
namespace MHConfigurator.ViewModels
{
class MainViewModel : ViewModelBase
{
public MainViewModel()
{
_mailProperties = new ObservableCollection<MailProperty>(DAL.GetDAL().MailPropertys);
//MailsTemplates = DAL.GetDAL().GetEmptyMailTemplates();
}
#region Fields
#region Backing Fields
private ObservableCollection<MailProperty> _mailProperties;
private MailProperty _currentProperty;
private string _searchString;
private MailProperty _originalCurrentProperty;
private bool _currentPropertyChanged = false;
private List<MailsTemplate> _mailsTemplates;
private int _selectedMailTemplate;
#endregion
public string SearchString
{
get
{
if (_searchString.IsNullOrEmpty()) return "";
return _searchString;
}
set
{
bool stringContains = _searchString != null && value.Contains(_searchString);
_searchString = value;
CurrentProperty = null;
//Not matter
}
}
public ObservableCollection<MailProperty> MailProperties
{
get { return _mailProperties; }
set
{
_mailProperties = value;
//OnPropertyChanged(new PropertyChangedEventArgs("MailProperties"));
OnPropertyChanged();
}
}
public MailProperty CurrentProperty
{
get { return _currentProperty; }
set
{/*
if ((_originalCurrentProperty != null)&&(_currentPropertyChanged)&&(_originalCurrentProperty!=_currentProperty)) //Если выбран другой объект и есть несохранённые изменения
{
MessageBoxResult result = MessageBox.Show("Есть несохранённые изменения. Сохранить?", "Несохранённые изменения", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
}
else
{
MailProperties[MailProperties.IndexOf(_currentProperty)] = _originalCurrentProperty; //Находим в коллекции изменённый объект и заменить его оригиналом
}
}
_originalCurrentProperty = Helper.DeepClone(_currentProperty); //Делаем резервную копию
SelectedMailTemplate = value.BodyID; //выставляем id шаблона
*/
_currentProperty = value;
// OnPropertyChanged(new PropertyChangedEventArgs("CurrentProperty"));
OnPropertyChanged();
}
}
public List<MailsTemplate> MailsTemplates
{
get { return _mailsTemplates; }
set
{
_mailsTemplates = value;
OnPropertyChanged();
}
}
public int SelectedMailTemplate
{
get { return _selectedMailTemplate; }
set
{
_selectedMailTemplate = value;
CurrentProperty.BodyID = value;
OnPropertyChanged();
}
}
#endregion
#region Commands
public ICommand NewCommand { get; private set; }
public ICommand SaveCommand { get; private set; }
public ICommand CancelCommand { get; private set; }
#region Execute
#endregion
#region CanExecute
#endregion
#endregion
}}
I have no idea.
I will be glad to any ideas.
P.S.: Sorry for my bad english.
This is my class:
public class ZuResults
{
public Direct_Matches[] direct_matches { get; set; }
public int found { get; set; }
public string query { get; set; }
public ZuResults()
{
}
}
public class Direct_Matches
{
public object[] data { get; set; }
public string[] headwords { get; set; }
public Metadata metadata { get; set; }
}
public class Metadata
{
public string pos { get; set; }
public string lang { get; set; }
}
This is the ListView to which I am trying to bind this class:
<ListView Grid.Row="0" Margin="0,50,0,0" x:Name="listZuResults"
SelectionMode="Single" Background="White"
ScrollViewer.VerticalScrollBarVisibility="Auto" ItemsSource="{Binding}"
BorderThickness="0,0,1,0" BorderBrush="DarkGray">
<ListView.ItemTemplate>
<DataTemplate>
<Grid BorderThickness="1,1,1,2" BorderBrush="LightGray" Width="350">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel VerticalAlignment="Center">
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Query" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Query" FontSize="15" FontWeight="Bold"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="txtQuery" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="{Binding query, Mode=TwoWay}" FontSize="12"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Found" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Results found" FontSize="15" FontWeight="Bold"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="txtFound" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="{Binding found, Mode=TwoWay}" FontSize="12"/>
<ListView ItemsSource="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=direct_matches[1]}">
<DataTemplate>
<Grid BorderThickness="1,1,1,2" BorderBrush="LightGray" Width="350">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel VerticalAlignment="Center">
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Metadata" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Metadata" FontSize="15" FontWeight="Bold"/>
<ListView ItemsSource="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=metadata}">
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="Pos" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="Pos" FontSize="15" FontWeight="Bold"/>
<TextBlock Margin="0,0,0,0" Grid.Row="0" x:Name="txtPos" Foreground="{Binding FontColor}" TextWrapping="Wrap" Text="{Binding pos}" FontSize="12"/>
</ListView>
</StackPanel>
</Grid>
</DataTemplate>
</ListView>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
When I set the ItemsSource of listZuResults in my MainPage.xaml code-behind, the only values that actually appear when I debug are those of txtQuery and txtFound. How do I display the rest of the data, for example 'pos' and 'lang'?
I have class
public class Clip
{
public string ID { get; set; }
public string Name { get; set; }
public int? Duration { get; set; }
}
And ObservableCollection
public ObservableCollection<Clip> _clipsFound;
public ObservableCollection<Clip> collection
{
get { return _clipsFound; }
set
{
_clipsFound = value;
OnPropertyChanged();
}
}
OnPropertyChanged() is invoked when I do
_clipsFound = collection
I want binding data from collection to ListBox with three columns: ID, Name, Duration
Initialize
ID = id;
collection = new ObservableCollection<Clip>();
_clipsFound = collection;
_clipsFound.Clear();
ICollection<Clip> ClipF = await Service.GetClips(ID);
ICollection<Clip> Clipcol = ClipF;
collection = new ObservableCollection<Clip>(Clipcol);
I try do this, but it doesn't work
<ListBox Grid.Row="2" ItemsSource="{Binding collection}" BorderBrush="Transparent" >
<ListBox.ItemTemplate>
<DataTemplate DataType="ui:Clip">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding Title}"
VerticalAlignment="Center"
HorizontalAlignment="Left"
TextTrimming="CharacterEllipsis"
Foreground="#FF4F4F4F"
FontSize="12"
Margin="55 0 0 0"/>
<TextBlock Grid.Column="1"
Margin="0 0 45 0"
Text="{Binding Duration}"
VerticalAlignment="Center"
HorizontalAlignment="Right"
FontSize="11"
Foreground="#FF4F4F4F"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
What did I do wrong?
You cannot send data from viewmodel to view without setting DataContext. DataContext is like channel or bridge between ViewModel and View.
This code sets DataContext:
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
Let's see work example:
Your ViewModel:
public class MainWindowViewModel
{
publicMainWindowViewModel
{
LoadData();
}
private void LoadData()
{
_clipsFound=new ObservableCollection<Clip>();
for(int startIndex=0; startIndex<10; startIndex++)
{
collection.Add(new Clip(){ID=startIndex, Name="Bob", Duration=startIndex++});
}
}
public ObservableCollection<Clip> _clipsFound;
public ObservableCollection<Clip> collection
{
get
{
return _clipsFound;
}
set
{
_clipsFound = value;
}
}
}
Your XAML:
<Window x:Class="DataGridSelectedItemsWpfApplication.MainWindow"
...The code omitted for the brevity...
xmlns:vm="clr-namespace:DataGridSelectedItemsWpfApplication.ViewModel"
Title="MainWindow" WindowStartupLocation="CenterScreen" Height="550" Width="525">
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<ListBox Grid.Row="2" ItemsSource="{Binding collection}" BorderBrush="Transparent" >
<ListBox.ItemTemplate>
<DataTemplate DataType="ui:Clip">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding ID}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="11" Margin="2" Foreground="#FF4F4F4F"/>
<TextBlock Grid.Column="1" Margin="2" Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" TextTrimming="CharacterEllipsis" Foreground="#FF4F4F4F" FontSize="12"/>
<TextBlock Grid.Column="2" Margin="2" Text="{Binding Duration}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="11" Foreground="#FF4F4F4F"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
There are many ways to set DataContext.
First time using a ListBox and after following this , I'm having issues having data actually display. The ListBox is just empty and white with no text in it.
I made a separate textbox to test an individual "Tweet" object out and it is indeed outputting what I want it to. I think my issue either lies in XAML or Tweets. But nothing looks out of place.
Tracing reveals that Tweets successfully adds a proper Tweet object with what I need. But my ListBox Count is always 0.
<Grid Opacity="0.8">
<Grid.Resources>
<local:Tweets x:Key="tweets"/>
</Grid.Resources>
<Rectangle Fill="Gray" Margin="1523,0,0,729" Height="321" Width="389">
<Rectangle.Effect>
<DropShadowEffect/>
</Rectangle.Effect></Rectangle>
<ListBox ItemsSource="{StaticResource tweets}" Height="321" Margin="340,40,1096,0" x:Name="twitterBox" VerticalAlignment="Top" Width="476">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
In my cs:
public class Tweet
{
public String imgSrc { get; set; }
public String user { get; set; }
public String tweet { get; set; }
public Tweet(String user, String tweet, String img)
{
this.imgSrc = img;
this.user = user;
this.tweet = tweet;
}
}
public class Tweets : ObservableCollection<Tweet>
{
public Tweets()
{
}
public void addTweet(Tweet tweet)
{
Add(tweet);
}
}
public void SomeFunction()
{
Tweets myTwitter = new Tweets();
myTwitter.addTweet(new Tweet(tweet.User.ScreenName, tweet.Text, tweet.User.ProfileImageUrl));
}
ItemTemplate code is ok but you should remove this Margin="1523,0,0,729".
ListBox is empty because items source is empty. You should add some items.
To add items in XAML you should add default constructor to Tweet class.
public class Tweet
{
public String imgSrc { get; set; }
public String user { get; set; }
public String tweet { get; set; }
public Tweet(){}
public Tweet(String user, String tweet, String img)
{
this.imgSrc = img;
this.user = user;
this.tweet = tweet;
}
}
And now you can write something like this:
...
<Grid.Resources>
<local:Tweets x:Key="tweets">
<local:Tweet imgSrc="imgSrc1" user="user1" tweet="tweet1" />
<local:Tweet imgSrc="imgSrc2" user="user2" tweet="tweet2" />
</local:Tweets>
</Grid.Resources>
...
Result:
Add items in code-behind.
To do that you should use function: FindResource (msdn).
XAML:
<Grid Name="mainGrid" Opacity="0.8">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.Resources>
<local:Tweets x:Key="tweets">
<local:Tweet imgSrc="imgSrc1" user="user1" tweet="tweet1" />
<local:Tweet imgSrc="imgSrc2" user="user2" tweet="tweet2" />
</local:Tweets>
</Grid.Resources>
<Button Content="Add new item" Click="Button_Click" />
<ListBox x:Name="twitterBox" ItemsSource="{StaticResource tweets}"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Code-behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
var coll = mainGrid.FindResource("tweets") as Tweets;
if (coll != null)
{
coll.Add(new Tweet("user", "name", "url"));
}
}
Second solution:
The better solution will be if you will create an instance of class Tweets in code behind.
XAML:
<Grid Name="mainGrid" Opacity="0.8">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Add new item" Click="Button_Click" />
<ListBox x:Name="twitterBox" ItemsSource="{Binding tweets}"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!--<Image Source="{Binding imgSrc}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>-->
<StackPanel Width="370">
<TextBlock Text="{Binding user}" FontSize="28" />
<TextBlock Text="{Binding tweet}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
tweets = new Tweets();
tweets.Add(new Tweet("user1", "name1", "url1"));
tweets.Add(new Tweet("user2", "name2", "url2"));
tweets.Add(new Tweet("user3", "name3", "url3"));
this.DataContext = this;
}
public Tweets tweets { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
tweets.Add(new Tweet("user4", "name4", "url4"));
}
}
You add tweets to a different collection than the one displayed by the listbox.