I made a shot app to exemplify my question:
Heres the window1.xaml
<Window
x:Class="TreeViewStepByStep.Window1"
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:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Width="400"
Height="600">
<Window.Resources />
<Grid>
<TreeView
Margin="0,21,0,0"
ItemsSource="{Binding Regions}"
HorizontalAlignment="Left"
Width="221">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate
ItemsSource="{Binding Type}">
<TextBlock
Text="{Binding Name}" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate
ItemsSource="{Binding Locations}">
<TextBlock
Text="{Binding Name}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock
Text="{Binding}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<Button
Content="Populate"
Height="23"
HorizontalAlignment="Left"
Margin="227,21,0,0"
Name="button2"
VerticalAlignment="Top"
Width="96"
Click="button2_Click" />
<Button
Content="Add child"
Height="23"
HorizontalAlignment="Left"
Margin="227,49,0,0"
Name="button3"
VerticalAlignment="Top"
Width="96"
Click="button3_Click" />
<Button
Content="Modify"
Height="23"
HorizontalAlignment="Left"
Margin="227,106,0,0"
Name="button4"
VerticalAlignment="Top"
Width="96"
Click="button4_Click" />
<Button
Content="Add root level"
Height="23"
HorizontalAlignment="Left"
Margin="227,135,0,0"
Name="button5"
VerticalAlignment="Top"
Width="96"
Click="button5_Click" />
</Grid>
</Window>
And here's the window1.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace TreeViewStepByStep
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
Collection<Region> regions;
public Window1()
{
InitializeComponent();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
Region sms = new Region("São Mateus do Sul")
{
Type =
{
new Types("Placemarks")
{
Locations =
{
"Pine trees",
"Barn",
"Phantom city"
}
},
new Types("Planning")
{
Locations =
{
"Geada",
"Por do sol"
}
},
}
};
Region others = new Region("Outros")
{
Type =
{
new Types("Placemarks")
{
Locations =
{
"Road",
"Waterfall"
}
},
new Types("Planning")
{
Locations =
{
"Moon"
}
},
}
};
regions = new Collection<Region>() { sms, others };
DataContext = new
{
Regions = regions
};
}
private void button3_Click(object sender, RoutedEventArgs e)
{
this.regions[1].Type.Add(new Types("New folder")
{
Locations =
{
"Test"
}
}
);
}
private void button4_Click(object sender, RoutedEventArgs e)
{
this.regions[0].Name = "Edited";
}
private void button5_Click(object sender, RoutedEventArgs e)
{
this.regions.Add(new Region("My new region"));
}
}
public class Region
{
public Region(string name)
{
Name = name;
Type = new ObservableCollection<Types>();
}
public string Name { get; set; }
public ObservableCollection<Types> Type { get; set; }
}
public class Types
{
public Types(string name)
{
Name = name;
Locations = new ObservableCollection<string>();
}
public string Name { get; private set; }
public ObservableCollection<string> Locations { get; set; }
}
}
My TreeView is bound to a hierarchical model (the regions variable). When I click "Populate" it binds the TreeView to this variable. When I click "Add Child" it adds a child element to the bound variable and it reflects on the TreeView. So far so good.
The problem arises when I try to modify the name of an existing element or try to add a root level node ("Modify" and "Add Root Level" buttons). Shouldn't these modifications reflect on the TreeView as well since it's bound to the collection?
As you have it now, the Collection will not notify the view when it is changed. You want to use an ObservableCollection instead of a normal Collection<T>. The ObservableCollection is coded to work with the UI and make sure the view is always updated with those changes through the CollectionChanged event. You use ObservableCollection with some of the others, but your Regions variable is a Collection.
You need to change the Collection type to ObservableCollection and needs to implement INotifyPropertyChanged on region class to send notification to View on edit.
C#
Window Class:
ObservableCollection<Region> regions;
Region Class:
public class Region : INotifyPropertyChanged
{
public Region(string name)
{
Name = name; Type = new ObservableCollection<Types>();
}
private string name;
public string Name
{
get { return name; }
set
{
name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
public ObservableCollection<Types> Type { get; set; }
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };
#endregion
}
Related
I have two windows in my project(MainWindow and one small window for some properties of controls of the MainWindow). In one Tab in the MainWindow there is a Grid divided to ten Columns. In each Column there are some Controls. Below is a sample code of my project.
I want if I check the Period(CheckBox in PropertiesWindow) the Label(MainWindow) to be "Period" and when I check the Frequency(CheckBox in PropertiesWindow) the Label(MainWindow) to be "Frequency".
I want, when I check one of the checkboxes at the PropertiesWindow (Period or Frequency), the Label (lb_freq1) at the MainWindow to change its Content according to the Content of the checked CheckBox. (Moreover, the selected units to be displayed at the time_div1(Label)).
FIRST SOLUTION:
XAML MainWindow:
<Window x:Class="wpf1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-wpf1"
mc:Ignorable="d"
Title="wpf1" Height="720" Width="1280" WindowStartupLocation="CenterScreen" Icon="kkk.bmp" Background="#FFE0E0E0" Foreground="#FF49A81D" BorderBrush="#FFB93838" >
<Grid>
<TabControl x:Name="tabControl">
<TabItem Header="Tab1">
<Grid>
<StackPanel>
<Label x:Name="lb_freq1" Content="Period" HorizontalAlignment="Center" Margin="0,10,0,0" />
<StackPanel Orientation="Horizontal" Margin="0" HorizontalAlignment="Center">
<TextBox x:Name="txt_freq1" Width="50" Height="20" HorizontalContentAlignment="Right" BorderThickness="1,1,0,1" HorizontalAlignment="Left" VerticalContentAlignment="Center"/>
<Label x:Name="time_div1" Content="us" Width="20" BorderThickness="0,1,1,1" Margin="0" HorizontalAlignment="Right" Height="20" Padding="0" BorderBrush="#FFABADB3" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" />
</StackPanel>
<Label x:Name="lb_width1" Content="Pulse Width" HorizontalAlignment="Center" Margin="0,10,0,0" />
<StackPanel Orientation="Horizontal" Margin="0" HorizontalAlignment="Center">
<TextBox x:Name="txt_width1" Width="50" Height="20" HorizontalContentAlignment="Right" BorderThickness="1,1,0,1" HorizontalAlignment="Left"/>
<Label x:Name="pv_div1" Content="us" Width="20" BorderThickness="0,1,1,1" Margin="0" HorizontalAlignment="Right" Height="20" Padding="0" BorderBrush="#FFABADB3" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />
</StackPanel>
<Button x:Name="Properties1" Content="Properties" Margin="10,30,10,10" HorizontalAlignment="Center" BorderBrush="Blue" Click="Properties1_Click" />
</StackPanel>
</Grid>
</TabItem>
</TabControl>
</Grid>
</Window>
EDITED
Code Behind MainWindow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using System.ComponentModel;
namespace wpf1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
ViewModel viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private void Properties1_Click(object sender, RoutedEventArgs e)
{
string res1 = lb_freq1.Content.ToString();
string res3 = time_div1.Content.ToString();
var newWindow = new PWMProperties();
newWindow.Owner = this;
newWindow.ShowDialog();
string result1 = newWindow.Value1;
if (result1 == null)
{
lb_freq1.Content = res1;
}
else
{
lb_freq1.Content = result1;
}
string result3 = newWindow.Unit1;
if (result3 == null)
{
time_div1.Content = res3;
}
else
{
time_div1.Content = result3;
}
}
}
}
XAML PropertiesWindow:
<Window x:Class="wpf1.PWMProperties"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:wpf1"
mc:Ignorable="d"
Title="Properties" Height="335" Width="285" ResizeMode="NoResize" BorderThickness="0" WindowStartupLocation="CenterOwner">
<Window.Resources>
<local:BoolConverter2 x:Key="Converter"></local:BoolConverter2>
<local:BoolConverter x:Key="Reverse"></local:BoolConverter>
</Window.Resources>
<Grid>
<StackPanel VerticalAlignment="Top" Margin="0,10,0,0" HorizontalAlignment="Center">
<StackPanel Orientation="Horizontal" Margin="0,0,0,20">
<StackPanel Margin="0,0,49,0">
<RadioButton x:Name="SelectPeriod" Content="Period" Margin="0,0,0,0" Click="SelectPeriod_Click" />
<ComboBox x:Name="PeriodUnits" Padding="3,2,2,2" IsReadOnly="True" IsEditable="True" Text="us" IsEnabled="{Binding ElementName=SelectPeriod, Path=IsChecked}" SelectionChanged="PeriodUnits_SelectionChanged"
ItemsSource="{Binding PeriodComboBoxItems}">
</ComboBox>
</StackPanel>
<StackPanel Margin="20,0,0,0">
<RadioButton x:Name="SelectFrequency" Content="Frequency" Click="SelectFrequency_Click" />
<ComboBox x:Name="FrequencyUnits" Padding="3,2,2,2" IsReadOnly="True" IsEditable="True" Text="Hz" IsEnabled="{Binding ElementName=SelectFrequency, Path=IsChecked}" SelectionChanged="FrequencyUnits_SelectionChanged"
ItemsSource="{Binding FrequencyComboBoxItems}">
</ComboBox>
</StackPanel>
</StackPanel>
</StackPanel>
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Margin="0">
<Button x:Name="OkButton" Content="OK" Margin="135,5,10,5" Click="OkButton_Click" Width="60" />
<Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="60" Margin="0,5,10,5" />
</StackPanel>
</Grid>
</Window>
EDITED
Code Behind PropertiesWindow:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.IO;
using System.Xml;
using System.Windows.Markup;
namespace wpf1
{
/// <summary>
/// Interaction logic for Analog.xaml
/// </summary>
public partial class PWMProperties : Window
{
public ObservableCollection<string> PeriodComboBoxItems { get; set; }
public ObservableCollection<string> FrequencyComboBoxItems { get; set; }
public ObservableCollection<string> PulseWidthComboBoxItems { get; set;}
public PWMProperties()
{
InitializeComponent();
this.DataContext = this;
this.PeriodComboBoxItems = new ObservableCollection<string>() { "us", "ms", "s" };
this.FrequencyComboBoxItems = new ObservableCollection<string>() { "Hz", "kHz", "MHz" };
this.PulseWidthComboBoxItems = new ObservableCollection<string>() { "us", "ms", "s" };
}
string val1, val2, unit1, unit2;
private void OkButton_Click(object sender, RoutedEventArgs e)
{
if (SelectPeriod.IsChecked == true)
{
val1 = "Period";
if (unit1 == null || unit1!="ms") unit1 = "us";
}
if (SelectFrequency.IsChecked == true)
{
val1 = "Frequency";
if (unit1 == null || unit1!="kHz") unit1 = "Hz";
}
DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
public string Value1 { get { return val1; } }
public string Value2 { get { return val2; } }
public string Unit1 { get { return unit1; } }
public string Unit2 { get { return unit2; } }
private void PeriodUnits_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
unit1 = PeriodUnits.SelectedItem.ToString();
}
private void FrequencyUnits_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
unit1 = FrequencyUnits.SelectedItem.ToString();
}
}
public class BoolConverter2 : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool v = (bool)value;
return v;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotSupportedException();
}
}
}
Second possible solution:
Then, I've added to my MainWindow code a ViewModel:
public class ViewModel : INotifyPropertyChanged
{
private string _value1 = "Period";
public event PropertyChangedEventHandler PropertyChanged;
public string Value1
{
get { return _value1; }
set
{
_value1 = value;
OnPropertyChanged("Value1");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
So, most of the code behind of the PropertiesWindow is deleted and I use Binding for the change of lb_freq1(Label) at the MainWindow.
<Label x:Name="lb_freq1" Content="{Binding Value1, Mode=TwoWay}" HorizontalAlignment="Center" Margin="0,10,0,0" />
I don't know how to continue from that state. I'm new to WPF and C#, and I would be thankful if someone could help me in any way.
MAIN ISSUE
I've edited my first solution, so if someone could take a look. What I managed to do now is almost what i want. But, there is a problem. I want, when I click on the OK.Button, the "settings" I made at Properties.Window should change the Labels at MainWindow. Although, when I click on the Cancel.Button or the Close.Button at the upper right corner, any changes made at the Properties.Window should not change the Labels at MainWindow.
Moreover, when I close the Properties.Window, and then open it again for a second time, the CheckBoxes and ComboBox.SelectedItems need to have the same state they had when the Properties.Window closed. But that doesn't happen.
You should set the DataContext of the two windows properly. Currently, you are setting and overriding it in multiple places. Here is my suggestions:
Use ElementName in your Binding in your windows, i.e., wpf1.PWMProperties and wpf1.MainWindow, whenever you want to Bind to a property in them. In other words, give them a name and Bind to them. For example:
<Window x:Class="wpf1.PWMProperties"
.....
Name="owner">
.....
<StackPanel Margin="0,0,49,0">
.....
ItemsSource="{Binding Path=PeriodComboBoxItems, ElementName=owner}">
</StackPanel>
use DataContext for Binding to Value1 in your ViewModel. Set the DataContext of both Windows to be the instance of your ViewModel:
public partial class MainWindow : Window
{
ViewModel viewModel = new ViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = viewModel;
}
private void Properties1_Click(object sender, RoutedEventArgs e)
{
var newWindow = new PWMProperties();
newWindow.Owner = this;
newWindow.DataContext = viewModel;
newWindow.Show();
}
}
This is the first time that I have worked with wpf and I'm lost as to what I am doing wrong. I want to bind my datagrid to my data and any changes made, have it update the database on a button click save.
Here is my C# code:
using System;
using System.Linq;
using System.Windows;
using WebPortalSourceId.data;
namespace WebPortalSourceId
{
public partial class MainWindow : Window
{
private SuburbanPortalEntities entity;
public MainWindow()
{
InitializeComponent();
entity = new SuburbanPortalEntities();
}
private void Search_Click(object sender, RoutedEventArgs e)
{
if (CompanyCode.Text.Length != 3)
{
MessageBox.Show("Invalid Company Code. It must be 3 characters in length.");
return;
}
FillDataGrid(GetCorporationId(CompanyCode.Text.ToUpper()));
}
public void FillDataGrid(Guid corporationId)
{
var list = (from s in entity.Sources
where s.CorporationId == corporationId
select new SourceRecord
{
SourceId = s.SourceId,
CorporationId = s.CorporationId,
Description = s.Description,
IsActive = s.IsActive,
Name = s.Name,
TokenId = s.TokenId
}).ToList();
SourceDataGrid.ItemsSource = list;
}
private Guid GetCorporationId(string companycode)
{
return (from cs in entity.CorporationStructures
where cs.Company == companycode &
cs.IsActive &
cs.Branch == null
select cs.CorporationId).FirstOrDefault();
}
private void Save_Click(object sender, RoutedEventArgs e)
{
entity.SaveChanges();
}
}
public class SourceRecord
{
public Guid SourceId { get; set; }
public Guid CorporationId { set; get; }
public Guid TokenId { set; get; }
public string Description { set; get; }
public string Name { set; get; }
public bool IsActive { set; get; }
}
}
And my xaml:
<Window x:Class="WebPortalSourceId.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Web Portal SourceId" Height="409" Width="744" WindowStartupLocation="CenterScreen" ResizeMode="CanResizeWithGrip">
<Grid>
<TextBox Name="CompanyCode" HorizontalAlignment="Left" Height="23" Margin="337,11,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="48" MaxLength="3" TextAlignment="Center" CharacterCasing="Lower"/>
<Label Content="Company Code" HorizontalAlignment="Left" Margin="240,10,0,0" VerticalAlignment="Top"/>
<DataGrid Name="SourceDataGrid" Margin="10,43,10,10" CanUserReorderColumns="False" CanUserResizeRows="False" HorizontalContentAlignment="Stretch" FontFamily="Microsoft YaHei"/>
<Button Name="Search" Content="Search" HorizontalAlignment="Left" Margin="390,11,0,0" VerticalAlignment="Top" Width="75" Height="23" Click="Search_Click"/>
<Button x:Name="Save" Content="Save" HorizontalAlignment="Right" Margin="0,11,183,0" VerticalAlignment="Top" Width="75" Height="23" Click="Save_Click"/>
</Grid>
</Window>
Not much to it. It does get the data from the database but when I make a change, the changes are not saving back.
What am I doing wrong?
You're binding the datagrid with the "list" variable, so any changes you make is affecting only that var, to automatically save the changes you must bind to the entity.Sources collection of your entity model.
SourceDataGrid.ItemsSource = entity.Sources
I have a requirement to change the selected node in a treeview which is hosted in a separate tab.
Further more, if the parent node is not expanded, I wish to expand the node.
After about an hour of fruitless searching through SO, Google, et al, I have decided to post a question.
I can find and expand the required node when it is all visible, but when the treeveiw is obscured by another tab item, it doesn't update. I'm also not entirely sure that the item is being 'selected' - in the debugger it says ISelected is true, and the IsExpanded property of the parent is also true.
I have simplified down my actual problem in the following lines of code:
XAML (Tab control which has two items, one is a button to reproduce the problem, and a treeview which should be updated):
<Window x:Class="TreeviewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TabControl>
<TabItem Header="Select">
<Button Content="Select Delta!" Click="ButtonBase_OnClick" />
</TabItem>
<TabItem Header="Tree">
<TreeView ItemsSource="{Binding NodesDisplay}" Name ="treTest">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=ChildrenDisplay}">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</TabItem>
</TabControl>
</Grid>
MainWindow code:
namespace TreeviewTest
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
public ObservableCollection<TreeNode> Nodes { get; set; }
public ICollectionView NodesDisplay { get; set; }
public MainWindow()
{
InitializeComponent();
Nodes = new ObservableCollection<TreeNode>
{
new TreeNode(new List<TreeLeaf>
{
new TreeLeaf{Name = "Alpha"},
new TreeLeaf{Name = "Beta"}
}){ Name = "One" },
new TreeNode(new List<TreeLeaf>
{
new TreeLeaf{Name = "Delta"},
new TreeLeaf{Name = "Gamma"}
}){ Name = "Two" }
};
NodesDisplay = CollectionViewSource.GetDefaultView(Nodes);
DataContext = this;
}
public class TreeNode
{
public string Name { get; set; }
public ObservableCollection<TreeLeaf> Children { get; private set; }
public ICollectionView ChildrenDisplay { get; private set; }
public TreeNode(IEnumerable<TreeLeaf> leaves)
{
Children = new ObservableCollection<TreeLeaf>(leaves);
ChildrenDisplay = CollectionViewSource.GetDefaultView(Children);
}
}
public class TreeLeaf
{
public string Name { get; set; }
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
EnsureCanIterateThroughCollection(treTest);
var rootLevelToSelect = Nodes.First(x => x.Name == "Two");
TreeViewItem root = treTest.ItemContainerGenerator.ContainerFromItem(rootLevelToSelect) as TreeViewItem;
EnsureCanIterateThroughCollection(root);
var leafLevelToSelect = rootLevelToSelect.Children.First(x => x.Name == "Delta");
TreeViewItem leaf = root.ItemContainerGenerator.ContainerFromItem(leafLevelToSelect) as TreeViewItem;
if (!root.IsExpanded)
root.IsExpanded = true;
leaf.IsSelected = true;
ReflectivelySelectTreeviewItem(leaf);
}
//Got this from another SO post - not sure is setting IsSelected on the node is actually doing what I think it is...
private static void ReflectivelySelectTreeviewItem(TreeViewItem node)
{
MethodInfo selectMethod = typeof(TreeViewItem).GetMethod("Select", BindingFlags.NonPublic | BindingFlags.Instance);
selectMethod.Invoke(node, new object[] { true });
}
private static void EnsureCanIterateThroughCollection(ItemsControl itemsControl)
{
if (itemsControl.ItemContainerGenerator.Status == GeneratorStatus.NotStarted)
ForceGenerateChildContent(itemsControl);
}
private static void ForceGenerateChildContent(ItemsControl itemsControl)
{
itemsControl.ApplyTemplate();
IItemContainerGenerator generator = itemsControl.ItemContainerGenerator;
GeneratorPosition position = generator.GeneratorPositionFromIndex(0);
using (generator.StartAt(position, GeneratorDirection.Forward, true))
{
for (int i = 0; i < itemsControl.Items.Count; i++)
{
DependencyObject dp = generator.GenerateNext();
generator.PrepareItemContainer(dp);
}
}
}
}
}
Also - another XAML snippet which does the same thing, but where the treeview is visible - you should be able to see the treeview expand and the item selected
<Window x:Class="TreeviewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Select Delta!" Click="ButtonBase_OnClick" />
<TreeView ItemsSource="{Binding NodesDisplay}" Name ="treTest" Grid.Row="1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=ChildrenDisplay}">
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
I would appreciate any help - My understanding of treeview's and WPF and databinding is that it doesn't work as nicely as something that gives you IsSynchronisedWithCurrentItem, which is why I am trying to handle updates to the treeview manually and am also trying to select items in the tree programmatically. If I am wrong on that front I would love a pointer to show me how to do it in a more 'WPF' way!
When a tab page is not visible, the controls are not created. Only once you switch to it are the controls created. Add a Boolean to your TreeNode viewmodel and bind the IsSelected property.
TreeNodeVm.cs:
using Microsoft.Practices.Prism.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
namespace TreeViewSelectTest
{
public class TreeNodeVm : NotificationObject
{
private TreeNodeVm Parent { get; set; }
private bool _isSelected = false;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
RaisePropertyChanged(() => IsSelected);
}
}
private bool _isExpanded = false;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
_isExpanded = value;
RaisePropertyChanged(() => IsExpanded);
}
}
public ObservableCollection<TreeNodeVm> Children { get; private set; }
public string Header { get; set; }
public TreeNodeVm()
{
this.Children = new ObservableCollection<TreeNodeVm>();
this.Children.CollectionChanged += Children_CollectionChanged;
}
void Children_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
foreach (var newChild in e.NewItems.Cast<TreeNodeVm>())
{
newChild.Parent = this;
}
}
}
public TreeNodeVm(string header, IEnumerable<TreeNodeVm> children)
: this()
{
this.Header = header;
foreach (var child in children)
Children.Add(child);
}
public void MakeVisible()
{
if (Parent != null)
{
Parent.MakeVisible();
}
this.IsExpanded = true;
}
public void Select()
{
MakeVisible();
this.IsSelected = true;
}
}
}
MainWindow.xaml:
<Window x:Class="TreeViewSelectTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<Button Content="Select B1" Click="btSelectB1_Click" />
</StackPanel>
<TabControl>
<TabItem Header="treeview">
<TreeView ItemsSource="{Binding Path=RootNode.Children}">
<TreeView.Resources>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected,Mode=TwoWay}" />
<Setter Property="IsExpanded" Value="{Binding Path=IsExpanded,Mode=TwoWay}" />
</Style>
</TreeView.Resources>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Header}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</TabItem>
<TabItem Header="the other item">
<Button />
</TabItem>
</TabControl>
</DockPanel>
</Window>
MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TreeViewSelectTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
RootNode = new TreeNodeVm("Root", new[]
{
new TreeNodeVm("A", new [] {
new TreeNodeVm("A1", new TreeNodeVm[0]),
new TreeNodeVm("A2", new TreeNodeVm[0]),
new TreeNodeVm("A3", new TreeNodeVm[0])
}),
new TreeNodeVm("B", new [] {
new TreeNodeVm("B1", new TreeNodeVm[0])
})
});
InitializeComponent();
this.DataContext = this;
}
public TreeNodeVm RootNode { get; private set; }
private void btSelectB1_Click(object sender, RoutedEventArgs e)
{
RootNode.Children[1].Children[0].Select();
}
}
}
When you call TreeNodeVm.Select(), it will update the future state of the visuals. Once the tab page gets switched back, the template is applied and the visuals are created as expanded and selected.
Do not know if this is specific to the Infragistics xamDataGrid but here goes the question:
Infragistics xamDataGrid exposes a property IsSynchronizedWithCurrentItem, which according to their documentation, synchronizes ActiveRecord with current item of a datasource that implements ICollectionView.
I have the following MasterDetails window with details (ContentControl) content based on the type of objects bound to the grid:
<DockPanel Name="dockPanel" LastChildFill="True">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="5" MaxHeight="5"/>
<RowDefinition/>
</Grid.RowDefinitions>
<igDP:XamDataGrid
Name="dataGrid"
IsSynchronizedWithCurrentItem="True"
SelectedItemsChanged="dataGrid_SelectedItemsChanged">
</igDP:XamDataGrid>
<GridSplitter
Style="{StaticResource blueHrizontalGridSplitter}"
Grid.Row="1" Grid.ColumnSpan="2"
BorderThickness="1" Margin="1,0"
HorizontalAlignment="Stretch" />
<ContentControl Grid.Row="2" Name="contentControl" />
</Grid>
</DockPanel>
In code behind, I am attempting to establish a link between the current item of the grid's data source to the DataContext of the details control in my MasterDetailsWindow's constructor as follows:
if (detailsControl != null)
{
var fwDControl = detailsControl as FrameworkElement;
if (fwDControl != null)
{
var b = new Binding() { ElementName = "dataGrid", Path = new PropertyPath("DataSource") };
fwDControl.SetBinding(DataContextProperty, b);
}
contentControl.Content = detailsControl;
}
else
{
var b = new Binding() { ElementName = "dataGrid", Path = new PropertyPath("DataSource") };
contentControl.SetBinding(ContentProperty, b);
b = new Binding("DataDetailsTemplate");
contentControl.SetBinding(ContentTemplateProperty, b);
}
When constructing a instance of the MasterDetails, the caller needs to provide either a detailsControl object or a string representing the URL to DataTemplate. If a detailsControl is provided, I execute code that checks if details is not null. Otherwise, I assume DataDetailsTemplate is provided instead.
I would have doubted my thinking here but if I construct an instance of the MasterDetails window, with a URL that resolves to the following dataTemplate:
<DataTemplate x:Key="LogDetailsTemplate">
<Grid Margin="5,5,5,0">
<TextBox Text="{Binding Message}" TextWrapping="WrapWithOverflow"/>
</Grid>
</DataTemplate>
selecting an item in the grid, displays the selected object's corresponding Message property in the TextBox.
However, if I provide a custom detailsControl object that derives from UserControl, selecting an item in the grid, does not cause change the DataContext of my detailsControl. Why is this?
TIA.
Whoa there!!!!! I may be wrong but it looks like you've come from a WinForms background and are trying to to do things in WPF the way you would for WinForms.
The good news is, you don't have to: Master detail can be handled using a simple forwardslash. In the example below, look at the bindings in MainWindow.xaml - the forwardslash indicates the currently selected item.
MODELS
public class Country
{
public string Name { get; set; }
public int Population { get; set; }
}
public class Continent
{
public string Name { get; set; }
public int Area { get; set; }
public IList<Country> Countries { get; set; }
}
VIEWMODELS
public class MainViewModel
{
private ObservableCollection<ContinentViewModel> _continents;
public ObservableCollection<ContinentViewModel> Continents
{
get { return _continents; }
set
{
_continents = value;
ContinentView = new ListCollectionView(_continents);
ContinentView.CurrentChanged += (sender, agrs) => CurrentContinent = ContinentView.CurrentItem as ContinentViewModel;
}
}
public ListCollectionView ContinentView {get; private set;}
/// <summary>
/// Use this to determine the current item in the list
/// if not willing to use \ notation in the binding.
/// </summary>
public ContinentViewModel CurrentContinent { get; set; }
}
public class ContinentViewModel
{
private Continent _model;
public Continent Model
{
get { return _model; }
set
{
_model = value;
Countries = _model.Countries
.Select(p => new CountryViewModel { Model = p })
.ToList();
}
}
public string Name
{
get { return Model.Name; }
}
public int Area
{
get { return Model.Area; }
}
public List<CountryViewModel> Countries { get; private set; }
}
public class CountryViewModel
{
public Country Model { get; set; }
public string Name
{
get { return Model.Name; }
}
public int Population
{
get { return Model.Population; }
}
}
MainWindow.xaml
<Window x:Class="XamDataGridMasterDetail.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Views="clr-namespace:XamDataGridMasterDetail.Views"
xmlns:igDP="http://infragistics.com/DataPresenter"
Title="MainWindow">
<Grid>
<StackPanel Orientation="Vertical">
<!-- Continent list -->
<igDP:XamDataGrid HorizontalAlignment="Left"
Margin="10,10,0,0"
Name="xamDataGrid1"
Height="300"
VerticalAlignment="Top"
DataSource="{Binding ContinentView}"
IsSynchronizedWithCurrentItem="True">
<igDP:XamDataGrid.FieldSettings>
<igDP:FieldSettings CellClickAction="SelectRecord" />
</igDP:XamDataGrid.FieldSettings>
<igDP:XamDataGrid.FieldLayouts>
<igDP:FieldLayout>
<igDP:FieldLayout.Settings>
<igDP:FieldLayoutSettings AutoGenerateFields="False" />
</igDP:FieldLayout.Settings>
<igDP:FieldLayout.Fields>
<igDP:Field Name="Name"
Label="Name" />
<igDP:Field Name="Area"
Label="Area" />
<igDP:UnboundField Label="# Countries"
Binding="{Binding Countries.Count}" />
</igDP:FieldLayout.Fields>
</igDP:FieldLayout>
</igDP:XamDataGrid.FieldLayouts>
</igDP:XamDataGrid>
<!-- Continent detail -->
<ListBox ItemsSource="{Binding ContinentView/Countries}"
DisplayMemberPath="Name"
IsSynchronizedWithCurrentItem="True"
Height="200" />
<!-- Country detail -->
<StackPanel Orientation="Horizontal">
<Label Content="Name: " />
<TextBlock Text="{Binding ContinentView/Countries/Name}" />
<Label Content="Population: " />
<TextBlock Text="{Binding ContinentView/Countries/Population}" />
</StackPanel>
</StackPanel>
</Grid>
</Window>
App.xaml.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using XamDataGridMasterDetail.ViewModels;
using System.Collections.ObjectModel;
using XamDataGridMasterDetail.Model;
namespace XamDataGridMasterDetail
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnSessionEnding(SessionEndingCancelEventArgs e)
{
base.OnSessionEnding(e);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var view = new MainWindow();
var vm = new MainViewModel();
vm.Continents = new ObservableCollection<ContinentViewModel>();
vm.Continents.Add(new ContinentViewModel
{
Model = new Continent
{
Name = "Australasia",
Area = 100000,
Countries = new[]
{
new Country
{
Name="Australia",
Population=100
},
new Country
{
Name="New Zealand",
Population=200
}
}
}
});
vm.Continents.Add(new ContinentViewModel
{
Model = new Continent
{
Name = "Europe",
Area = 1000000,
Countries = new[]
{
new Country
{
Name="UK",
Population=70000000
},
new Country
{
Name="France",
Population=50000000
},
new Country
{
Name="Germany",
Population=75000000
}
}
}
});
view.DataContext = vm;
view.Show();
}
}
}
I want to develop dialog for editing objects that make use of polymorphism. Currently I'm using this pattern:
MyObject.cs:
using System;
namespace WpfApplication3
{
public class MyObject
{
public string Title { get; set; }
public MySettings Settings { get; set; }
}
public abstract class MySettings
{
public abstract string GetSettingsString();
}
public class MyBoolSettings : MySettings
{
public bool BoolSetting { get; set; }
public override string GetSettingsString()
{
return "BoolSetting = " + BoolSetting;
}
}
public class MyStringSettings : MySettings
{
public string StringSetting { get; set; }
public override string GetSettingsString()
{
return "StringSetting = " + StringSetting;
}
}
}
MainWindow.xaml:
<Window x:Class="WpfApplication3.EditMyObjectDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="EditMyObjectDialog" Height="350" Width="350">
<StackPanel Margin="20">
<TextBlock Text="Title" />
<TextBox Name="txtTitle" />
<RadioButton Name="rdBoolSettings" Content="BoolSettings" IsChecked="True" Margin="0, 20, 0, 0" />
<CheckBox Name="chBool" Content="True" Margin="20, 0, 0, 20" />
<RadioButton Name="rdStringSettings" Content="StringSettings" />
<TextBox Name="txtString" Margin="20, 0, 0, 20"/>
<Button Content="OK" Click="OK_click" />
<Button Content="Cancel" Click="Cancel_click" Margin="0, 10" />
</StackPanel>
</Window>
MainWindow.xaml.cs:
using System.Windows;
namespace WpfApplication3
{
public partial class EditMyObjectDialog : Window
{
public MyObject Result { get; set; }
public EditMyObjectDialog(MyObject objectToEdit)
{
InitializeComponent();
txtTitle.Text = objectToEdit.Title;
if (objectToEdit.Settings is MyBoolSettings)
{
rdBoolSettings.IsChecked = true;
chBool.IsChecked = (objectToEdit.Settings as MyBoolSettings).BoolSetting;
}
if (objectToEdit.Settings is MyStringSettings)
{
rdBoolSettings.IsChecked = true;
txtString.Text = (objectToEdit.Settings as MyStringSettings).StringSetting;
}
}
private void OK_click(object sender, RoutedEventArgs e)
{
Result = new MyObject() { Title = txtTitle.Text };
if (rdBoolSettings.IsChecked == true)
Result.Settings = new MyBoolSettings() { BoolSetting = chBool.IsChecked == true };
if (rdStringSettings.IsChecked == true)
Result.Settings = new MyStringSettings() { StringSetting = txtString.Text };
DialogResult = true;
}
private void Cancel_click(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
}
ExternalCode:
var f = new EditMyObjectDialog(myObject);
if (f.ShowDialog() == true)
myObject = f.Result;
I belive there is much better design pattern that uses data binding etc. So basically I have two questions.
How to make data binding not to
modify object until user hits 'OK'?
How to correctly handle 'Settings'
property? What to do when user
switches setting's type?
What I believe you're looking for is a combination of DataBinding and DataTemplating. DataTemplating will allow you to define different visual elements for different business objects (in this case MyBooleanSettings and MyStringSettings. DataBinding will allow the visual elements to update and be updated my the data in the business objects.
Example (xaml):
<Window DataContext={Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<DataTemplate DataType={x:Type local:MyObject}">
<TextBlock Text={Binding Title}" />
<ContentPresenter Content="{Binding Settings}" />
</DataTemplate>
<DataTemplate DataType={x:Type local:MyObject}">
<TextBox Text={Binding
</DataTemplate>
<DataTemplate DataType={x:Type local:MyBoolSettings}>
<CheckBox IsChecked="{Binding BoolSetting}" />
</DataTemplate>
<DataTemplate DataType={x:Type local:MyStringSettings}>
<TextBox Text="{Binding StringSetting}" />
</DataTemplate>
</Window.Resources>
<ContentPresenter Content="{Binding ObjectToEdit}" />
</Window>
Then in the code behind define:
public MyObject ObjectToEdit { get; set; }
Finally update your objects:
public class MySettings : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(sting s)
{
if(PropertyChanged != null)
{
PropertyChanged(s);
}
}
}
public class BoolSettings : MySettings
{
bool _value;
bool BoolSetting
{
get { return _value; }
set
{
if(_value != value)
{
_value = value;
OnPropertyChanged("BoolSetting");
}
}
}
}
If however you really need to control when the view and object sync you should use the UpdateSourceTrigger property on the corresponding bindings.
If you want some additional reading I recommend: http://msdn.microsoft.com/en-us/library/ms752347.aspx
DataBinding is Simple . You can create an instance of MyObject and assign it to the DataContext property of the Form.
this.DataContext=MyObject;
And define binding for individual elements.
<TextBox Name="txtTitle" Text="{Binding Path=Title,Mode=TwoWay }" />
Setting mode as two way will affect the object as you make change in UI. One way will show the values.
How to make data binding not to modify object until user hits 'OK'?
Create a copy of the MyObject instance. In the Result property get method, return copy if user hit cancel (return unchanged copy) or if user hit OK, return the changed MyObject instance.
How to correctly handle 'Settings' property? What to do when user switches setting's type?
Whats the problem?