How to change the background color of a Silverlight DataGridRow? - silverlight-4.0

I have a Silverlight DataGrid bound to a collection of MyObjects. MyObject has a boolean field called IsHighlighted.
I would like to change the row's background color when this value is true. And to have it changed back if it becomes false.
I already tried by using the Loading_Rowevent (as explained here), but it didn't work for me, as this event is only called once, and my objetcs all have the boolean value set to false at this time (it only becomes truc when another component is selectes; this works, I checked the values).
Anybody has a clue ? Thanks in advance !
Update: I made a test application to illustrate, it reproduces my problem.
<navigation:Page x:Class="AViews.Tests"
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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignWidth="640" d:DesignHeight="480"
Title="Tests Page">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<sdk:DataGrid Grid.Row="0" ItemsSource="{Binding AllItems, Mode=TwoWay}" AutoGenerateColumns="False" LoadingRow="DataGrid_LoadingRow">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding Value1}" Header="Value1" />
<sdk:DataGridTextColumn Binding="{Binding Value2}" Header="Value2"/>
<sdk:DataGridCheckBoxColumn Binding="{Binding IsHighlighted}" Header="Is Highlighted" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
<Button Content="Change !" Grid.Row="1" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>
</navigation:Page>
public partial class Tests : Page, INotifyPropertyChanged
{
private SampleConverter bgConverter = new SampleConverter();
Random r = new Random();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private ObservableCollection<Sample> allItemsField = new ObservableCollection<Sample>();
public ObservableCollection<Sample> AllItems
{
get
{
return this.allItemsField;
}
set
{
if (this.allItemsField != value)
{
this.allItemsField = value;
this.OnPropertyChanged("AllItems");
}
}
}
public Tests()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var tmp = Enumerable.Range(0, 100).Select(f => new Sample(f)).ToList();
foreach (var item in tmp)
{
item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
}
var coll = new ObservableCollection<Sample>(tmp);
this.AllItems = coll;
}
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
this.OnPropertyChanged("AllItems");
}
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
Binding b = new Binding("IsHighlighted")
{
Mode = BindingMode.OneWay,
Converter = this.bgConverter,
ValidatesOnExceptions = true
};
e.Row.SetBinding(DataGridRow.BackgroundProperty, b);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (var item in this.AllItems)
{
item.IsHighlighted = r.Next(1000) % 2 == 0;
}
}
}
public class Sample: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private string value1Field = string.Empty;
public string Value1
{
get
{
return this.value1Field;
}
set
{
if (this.value1Field != value)
{
this.value1Field = value;
this.OnPropertyChanged("Value1");
}
}
}
private string value2Field = string.Empty;
public string Value2
{
get
{
return this.value2Field;
}
set
{
if (this.value2Field != value)
{
this.value2Field = value;
this.OnPropertyChanged("Value2");
}
}
}
private bool isHighlightedField = false;
public bool IsHighlighted
{
get
{
return this.isHighlightedField;
}
set
{
if (this.isHighlightedField != value)
{
this.isHighlightedField = value;
this.OnPropertyChanged("IsHighlighted");
}
}
}
public Sample(int index)
{
this.Value1 = string.Format("Value1 #{0}", index);
this.Value2 = string.Format("Value2 #{0}", index);
}
}
public class SampleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool val = (bool)value;
SolidColorBrush ret = val ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Green);
return ret;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And the result can be seen on those pictures:
When I first arrive on the page.
I click the button, which sets some (random) values to true. As you can see, the binding is updated, not the UI.
I use the scrollbar, go to the end, and come back, and Oh! wonderful! All the rows are correctly colored :-(

Related

Assignment to ColumnDefinitions with binding to xamarin forms

I need the column to be dynamic and the values ​​to change when I click the button.
I made a method that, when activated, will pass the value to a variable that will be used for association through binding.
private void clickedColumnDefinition()
{
ColumnDefinition1 = 420;
}
The property this method have a declared GrindLenght:
private GridLength _columnDefinition1;
public GridLength ColumnDefinition1 {
get { return _columnDefinition1; }
set { SetProperty(ref _columnDefinition1, value); }
}
In xaml define the column like this:
<ColumnDefinition Width="{Binding ColumnDefinition1, Converter={StaticResource numberToGridLengthConverter}}"/>
The converter I'm using is this one, but nothing happens when I press the button.
public class NumberToGridLengthConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var numberValue = (double)value;
return new GridLength(numberValue, GridUnitType.Star);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var gridLength = (GridLength)value;
return gridLength.Value;
}
}
what can be wrong?
If you want to set the RowDefinition's Height to a Dynamic value. You can do as follows:
1.created a view model RowHeightClass
public class RowHeightClass: INotifyPropertyChanged
{
bool swith;
//public GridLength rowFirstHeight { set; get; }
GridLength _rowFirstHeight;
public GridLength RowFirstHeight
{
get => _rowFirstHeight;
set => SetProperty(ref _rowFirstHeight, value);
}
//public GridLength rowSecondHeight { set; get; }
GridLength _rowSecondHeight;
public GridLength RowSecondHeight
{
get => _rowSecondHeight;
set => SetProperty(ref _rowSecondHeight, value);
}
public RowHeightClass()
{
//initial RowFirstHeight and RowSecondHeight
RowFirstHeight = new GridLength(15);
RowSecondHeight = new GridLength(15);
}
public ICommand ResetHeightCommand => new Command(resetHeight);
private void resetHeight()
{ //reset RowFirstHeight and RowSecondHeight
if (!swith)
{
RowFirstHeight = new GridLength(50);
RowSecondHeight = new GridLength(50);
}
else {
RowFirstHeight = new GridLength(15);
RowSecondHeight = new GridLength(15);
}
swith = !swith;
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
2.bind the properties in MainPage.xaml as follows:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DynamicHeightApp.MainPage">
<StackLayout>
<Grid BackgroundColor="Orange">
<Grid.RowDefinitions>
<RowDefinition Height="{Binding RowFirstHeight}" />
<RowDefinition Height="{Binding RowSecondHeight}"/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Text="Testing Color Change on this one" TextColor="Red"/>
<Label Grid.Row="1" Text="Testing Height" />
<Label Grid.Row="2" Text="Testing Height Change on this one through binding"/>
</Grid>
<Button Text="reset" Command="{Binding ResetHeightCommand}"/>
</StackLayout>
</ContentPage>
3.MainPage.xaml.cs
public partial class MainPage : ContentPage
{
RowHeightClass rowHeightClass;
public MainPage()
{
InitializeComponent();
rowHeightClass = new RowHeightClass();
BindingContext = rowHeightClass;
}
}
Note:
I added two properties RowFirstHeight and RowSecondHeight and implemented interface INotifyPropertyChanged for this view model, if we change the value of above properties, the UI will update automatically.

Binding value is not updating on entry control from other xaml

I have an entry control in my XAML where I set the initial value on page appear through data binding. Initially the value is appearing but when I am updating it from another view model it is not getting updated on UI.
Below is the XAML code and XAML.CS
<ListView
x:Name="workList"
Grid.Row="2"
SeparatorColor="{DynamicResource AccentColor}"
ItemsSource="{ Binding WorkItems }"
Margin="5"
CachingStrategy="RecycleElement"
RowHeight="440"
SeparatorVisibility="Default"
SelectionMode="None"
HasUnevenRows="False">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<local:LoadItemPutawayTemplate />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-
compatibility/2006"
mc:Ignorable="d"
x:Class="Sanipex.LoadItemPutawayTemplate">
<Grid
RowSpacing="0"
Padding="0"
Margin="0,10,0,0"
>
<Grid.RowDefinitions>
<RowDefinition
Height="*" />
</Grid.RowDefinitions>
<Entry
x:Name="OverrideLoc"
Grid.Row="0"
TextColor="Black"
WidthRequest="110"
Text="{Binding toLocation}"
grial:EntryProperties.BorderCornerRadius="10"
grial:EntryProperties.BorderStyle="RoundRect"
grial:EntryProperties.BorderColor="Black"
HorizontalOptions="StartAndExpand"
VerticalOptions="Center"
Focused="OverrideLoc_Focused"
TextChanged="OverrideLoc_TextChanged"
grial:EntryProperties.HorizontalPadding="5"
FontAttributes="Bold"
PlaceholderColor="Black"
FontSize="20"/>
</Grid>
public partial class ItemPutAway : ContentPage
{
private static ItemPutAwayViewModel obj;
public ItemPutAway()
{
InitializeComponent();
obj = new ItemPutAwayViewModel();
BindingContext = obj;
}
public static ItemPutAwayViewModel itemPutAwayViewModel
{
get
{
return obj;
}
}
protected override async void OnAppearing()
{
obj.LoadData();
}
}
Below is my first view model code
public class ItemPutAwayViewModel : INotifyPropertyChanged
{
private IList<WorkItem> workItems;
public event PropertyChangedEventHandler PropertyChanged;
public string ltoLocation;
public string toLocation
{
get => ltoLocation;
set
{
ltoLocation = value;
OnPropertyChanged(nameof(toLocation));
}
}
public IList<WorkItem> WorkItems
{
get => workItems;
set
{
workItems = value;
OnPropertyChanged(nameof(WorkItems));
}
}
public void LoadData()
{
WorkItems = App.dataManager.GetItemPutAwayWorks();
}
public void setLocation(string _location)
{
toLocation = _location;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Below is the code through which I am trying to update the toLocation binding value to different value from another XAML page as below:
public partial class AvailableLocationsPopUp : PopupPage
{
private static AvailableLocationViewModel obj;
public AvailableLocationsPopUp(WorkItem _workItem)
{
InitializeComponent();
obj = new AvailableLocationViewModel(gWorkItem.itemid);
BindingContext = obj;
}
private void OnClose(object sender, EventArgs e)
{
PopupNavigation.Instance.PopAsync();
}
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
Location content = e.Item as Location;
ItemPutAway.itemPutAwayViewModel.setLocation("ABC-XYZ");
PopupNavigation.Instance.PopAsync();
}
}
As I mentioned in the discussion, you have to also implement the INotifyPropertyChanged interface of the class WorkItem.
Implement INotifyPropertyChanged in ItemPutAwayViewModel will only help for changes in the WorkItems(like add or remove one WorkItem), not the changes inside the WorkItem.
So, the code should be:
public class WorkItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _toLocation;
public string toLocation
{
get => _toLocation;
set
{
_toLocation = value;
NotifyPropertyChanged();
}
}
protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

PropertyChangedCallback is not getting fired during callback when a value in ViewModel is changed

I have a view that uses the SearchBox user control, The SearchBox has two radio buttons to select the search modes - Instant and delayed. I have binded the searchmodes to SearchMode property, and also I have created a custom dependency property for the Search Mode.
View
<controls:SearchBox Grid.Row="0"
HorizontalAlignment="Right"
Margin="2" Width="200"
SearchMode="{Binding DataContext.SearchMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }" />
ViewModel.cs
private Mode mSearchMode;
public Mode SearchMode
{
get
{
return mSearchMode;
}
set
{
mSearchMode = value;
NotifyOfPropertyChange();
}
}
// Called when application is restarted.
private void ActivateLastSelectedSearchMode(Mode lastselectedMode)
{
// Sets the last selected mode to the search mode
SearchMode = lastselectedMode;
}
public enum Mode
{
Instant,
Delayed,
}
SearchBox.xaml
<UserControl x:Class = "abc.SearchBox"
DataContext="{Binding RelativeSource={RelativeSource Self}}" >
<UserControl.Resources>
<converters:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
</UserControl.Resources>
<StackPanel Orientation="Vertical">
<RadioButton Content="{lex:Loc SearchBox:SearchModelInstatOption}"
IsChecked="{Binding Path=SearchMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Mode.Instant}}" />
<RadioButton Content="{lex:Loc SearchBox:SearchModeDelayedOption}"
IsChecked="{Binding Path=SearchMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Mode.Delayed}}" />
</StackPanel>
</UserControl>
SearchBox.xaml.cs
public partial class SearchBox : UserControl
{
public static DependencyProperty SearchModeProperty =
DependencyProperty.Register(
"SearchMode",
typeof(Mode),
typeof(SearchBox),
new FrameworkPropertyMetadata(default(Mode), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsSearchModeChanged));
static void OnIsSearchModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var searchBox = obj as SearchBox;
searchBox.SearchMode = (Mode)e.NewValue;
}
public Mode SearchMode
{
get { return (Mode)GetValue(SearchModeProperty); }
set { SetValue(SearchModeProperty, value); }
}
}
I want the OnIsSearchModeChanged() to be fired each time when SearchMode is set during call back i e, ActivateLastSelectedSearchMode() is invoked in ViewModel.cs. I am absolutely clueless..where I am missing, I am unable to achieve success.
//snip
private Mode mSearchMode;
public Mode SearchMode
{
get
{
return mSearchMode;
}
set
{
mSearchMode = value;
NotifyOfPropertyChange(()=>SearchMode); //Change
}
}
does the reflected change make any difference? Other option would be to create a custom convention for your user control
You should create an Event in you View Model and subscribe to it from your code behind.
In your View Model :
public event SearchModeAction SearchModeChanged;
public delegate void SearchModeAction(object sender, EventArgs e);
public void SearchModeHasChanged()
{
SearchModeAction Handler = SearchModeChanged;
if (Handler != null)
{
Handler(this, null);
}
}
private void ActivateLastSelectedSearchMode(Mode lastselectedMode)
{
// Sets the last selected mode to the search mode
SearchMode = lastselectedMode;
SearchModeHasChanged()
}
In your Code Behind :
private void Window_Loaded(object sender, RoutedEventArgs e)
{
((YourViewModelClass)DataContext).SearchModeChanged += OnIsSearchModeChanged;
}
private void OnIsSearchModeChanged(object sender, EventArgs e)
{
var searchBox = obj as SearchBox;
searchBox.SearchMode = (Mode)e.NewValue;
}
This way each time you arrive in your ActivateLastSelectedSearchMode method in your View Model, you will call your OnIsSearchModeChanged method in your View.
Ahh..the reason was the EnumToBooleanConverter.
Though the value of 'parameter' and 'value' was same, There was a difference between their object types as both were referencing to different namespaces. So I created a public enum called 'Mode' and ensured that the 'Instant' and 'Delayed' reference to the same namespace.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return false;
}
return value.Equals(parameter); // This always returned false despite the values being the same
}

How can I add KeyUp event for my UserControl?

I have a user control that working like WatermarkPasswordBox and I want to add KeyUp event for my user control's PasswordBox's Key Up event. How can I do it?
<UserControl
x:Class="Windows8.StoreApp.Common.CustomControls.WatermarkPasswordTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows8.StoreApp.Common.CustomControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<PasswordBox x:Name="passwordB" GotFocus="PasswordBox_GotFocus" LostFocus="PasswordBox_LostFocus" PasswordChanged="passwordB_PasswordChanged" Style="{StaticResource AkbankControlStyleWatermarkPasswordBoxLoginFormInputPasswordBox}"></PasswordBox>
<TextBlock x:Name="lblWaterMark" Tapped="lblWaterMark_Tapped" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,4,10,4" Opacity="0.8" FontFamily="Segoe UI" FontSize="16" Foreground="#FF8E8E8E" FontWeight="SemiBold"></TextBlock>
</Grid>
public WatermarkPasswordTextBox()
{
this.InitializeComponent();
}
private void PasswordBox_GotFocus(object sender, RoutedEventArgs e)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
private void PasswordBox_LostFocus(object sender, RoutedEventArgs e)
{
if ((sender as PasswordBox).Password.Length == 0)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Visible;
}
}
private void passwordB_PasswordChanged(object sender, RoutedEventArgs e)
{
if ((sender as PasswordBox).Password.Length != 0)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
private void lblWaterMark_Tapped(object sender, TappedRoutedEventArgs e)
{
lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
passwordB.Focus(Windows.UI.Xaml.FocusState.Pointer);
}
private string _watermark=String.Empty;
public string Watermark
{
get
{
_watermark = lblWaterMark.Text;
return _watermark;
}
set
{
SetProperty<string>(ref _watermark, value, "Watermark");
lblWaterMark.Text = _watermark;
}
}
private int _lenghtMax;
public int LenghtMax
{
get
{
if (passwordB != null)
{
_lenghtMax = passwordB.MaxLength;
return _lenghtMax;
}
else
{
return 0;
}
}
set
{
if (passwordB != null)
{
SetProperty<int>(ref _lenghtMax, value, "LenghtMax");
passwordB.MaxLength = _lenghtMax;
}
}
}
private string _passText = String.Empty;
public string PassText
{
get
{
if (passwordB != null)
{
_passText = passwordB.Password;
return _passText;
}
else
{
return String.Empty;
}
}
set
{
if (passwordB != null)
{
SetProperty<string>(ref _passText, value, "PassText");
passwordB.Password = _passText;
passwordB_PasswordChanged(passwordB, null);
}
else
{
SetProperty<string>(ref _passText, value, "PassText");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I want to use like this;
and this Key_Up will equal to mycontrol's PasswordBox' key up event.
Thanks.
public event KeyEventHandler RelayedKeyUp
{
add
{
passwordB.KeyUp += value;
}
remove
{
passwordB.KeyUp -= value;
}
}

How binding data depending on the value?

I have ObservableCollection and value that need to find the item in the collection. any ideas? (p.s converter not good idea, because i have many collections)
This functionality (applying a filter) belongs into the ViewModel. Here is an easy example for illustration.
You might also want to look at the CollectionViewSource for a more refined version of the same concept.
Xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" >
<ListBox ItemsSource="{Binding MyClasses}" DisplayMemberPath="Name" Margin="5" />
<ListBox ItemsSource="{Binding MyFilteredClasses}" DisplayMemberPath="Name" Margin="5" />
<TextBox Text="{Binding MySelectedClass.Name}" Margin="5" />
</StackPanel>
</Window>
ViewModel:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
namespace WpfApplication1
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private ObservableCollection<Class1> _myClasses;
public ObservableCollection<Class1> MyClasses { get { return _myClasses; } set { _myClasses = value; OnPropertyChanged("MyClasses"); } }
private List<Class1> _myFilteredClasses;
public List<Class1> MyFilteredClasses { get { return _myFilteredClasses; } set { _myFilteredClasses = value; OnPropertyChanged("MyFilteredClasses"); } }
private Class1 _mySelectedClass;
public Class1 MySelectedClass { get { return _mySelectedClass; } set { _mySelectedClass = value; OnPropertyChanged("MySelectedClass"); } }
public ViewModel()
{
MyClasses = new ObservableCollection<Class1>()
{
new Class1() { Name = "Connelly" },
new Class1() { Name = "Donnelly" },
new Class1() { Name = "Fonnelly" },
new Class1() { Name = "McGregor" },
new Class1() { Name = "Griffiths" }
};
// filter your ObservableCollection by some criteria, and bind to the result (either another list, or just one item)
MyFilteredClasses = MyClasses.Where(c => c.Name.EndsWith("onnelly")).ToList();
MySelectedClass = MyClasses.FirstOrDefault(c => c.Name.StartsWith("Mc"));
}
}
public class Class1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private string _name;
public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } }
}
}