Skip to content

Instantly share code, notes, and snippets.

@julesx
Created April 1, 2014 15:48
Show Gist options
  • Save julesx/9916910 to your computer and use it in GitHub Desktop.
Save julesx/9916910 to your computer and use it in GitHub Desktop.
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication12
{
public partial class MainWindow : INotifyPropertyChanged
{
public ObservableCollection<MyVm> MyCollection { get; set; }
private MyVm _selectedItem;
public MyVm SelectedItem {
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
public MainWindow()
{
InitializeComponent();
MyGlobals.MainWindow = this;
MyCollection = new ObservableCollection<MyVm>();
MyCollection.Add(new MyVm());
MyCollection.Add(new MyVm());
MyCollection.Add(new MyVm());
DataContext = this;
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
SelectedItem = MyCollection.First();
}
#region Property Changes
public void NotifyPropertyChanged(string _property)
{
OnPropertyChanged(_property);
}
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
#endregion
}
public static class MyGlobals
{
public static MainWindow MainWindow;
}
public class MyVm
{
}
public class MySelector : DataTemplateSelector
{
public DataTemplate NoSelectionTemplate { get; set; }
public DataTemplate ItemTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (MyGlobals.MainWindow.SelectedItem != null)
return ItemTemplate;
return NoSelectionTemplate;
}
}
}
<Window x:Class="WpfApplication12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication12="clr-namespace:WpfApplication12"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="NoSelectionTemplate">
<TextBlock Text="No selection, I Require access to the entire collection" />
</DataTemplate>
<DataTemplate x:Key="ItemTemplate">
<TextBlock Text="I Represent a single item of the collection" />
</DataTemplate>
<wpfApplication12:MySelector x:Key="MySelector" ItemTemplate="{StaticResource ItemTemplate}" NoSelectionTemplate="{StaticResource NoSelectionTemplate}" />
</Window.Resources>
<StackPanel Orientation="Vertical">
<ContentPresenter Content="{Binding}" ContentTemplateSelector="{StaticResource MySelector}" />
<Button Click="ButtonBase_OnClick" Content="Select Item" Margin="0,10,0,0"></Button>
</StackPanel>
</Window>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment