Expanding/selecting a treeview node when it is not currently visible - c#

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.

Related

WPF TwoWay Binding not work with CustomControl in Template

I have some problems with my Custom Control - Two way binding don't work when I use it in template.
So I have created template xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
xmlns:controls="clr-namespace:GUIControls;assembly=GUIControls"
>
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
xmlns:controls="clr-namespace:GUIControls;assembly=GUIControls"
>
<ControlTemplate x:Key="YParamCombo" TargetType="ContentControl">
<controls:ParamCombo Header="MY CONTROL TEMPLATE"
Items="{Binding Items}"
PCValue="{Binding Codes[MY_CONTROL_TEMPLATE], Mode=TwoWay}"
Required="True"
MultiSelect="False"/>
</ControlTemplate>
<ControlTemplate x:Key="YComboBox" TargetType="ContentControl">
<ComboBox DisplayMemberPath="Name"
StaysOpenOnEdit="True"
ItemsSource="{Binding Items}"
SelectedValue="{Binding Codes[STANDARD_TEMPLATE], Mode=TwoWay}"
SelectedValuePath="Code"/>
</ControlTemplate>
MainWindow.xaml
<Window x:Class="WpfApp1.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-namespace:WpfApp1"
mc:Ignorable="d"
xmlns:controls="clr-namespace:GUIControls;assembly=GUIControls"
Title="MainWindow" Height="250" Width="525">
<Grid Margin="0,0,0,-1">
<Button Margin="62,162,299,4" Content="Show Codes-1" Click="Button_Click2"></Button>
<StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<HeaderedContentControl Header="STANDARD CONTROL XAML" >
<ComboBox DisplayMemberPath="Name"
StaysOpenOnEdit="True"
ItemsSource="{Binding Items}"
SelectedValue="{Binding Codes[STANDARD_XAML]}"
SelectedValuePath="Code"/>
</HeaderedContentControl>
<HeaderedContentControl Header="STANDARD CONTROL TEMPLATE" >
<ContentControl Height="23" Template="{StaticResource YComboBox}"/>
</HeaderedContentControl>
<ContentControl Height="44" Template="{StaticResource YParamCombo}">
</ContentControl>
<controls:ParamCombo Header="MY CONTROL XAML"
Items="{Binding Items}"
PCValue="{Binding Codes[MYCONTROL_XAML], Mode=TwoWay}"
Required="True"
MultiSelect="False"/>
</StackPanel>
</Grid>
cs
using System.Linq;
using System.Windows;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = new WModel();
InitializeComponent();
}
private WModel vm { get { return (DataContext as WModel); } }
private void Button_Click2(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Join(";", vm.Codes._codes.Select(x => x.Key + "=" + x.Value).ToArray()));
}
}
}
using GUIControls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace WpfApp1
{
public class WModel
{
public WModel()
{
Codes = new CodesClass();
}
public string Caption { get; set; }
public ObservableCollection<Dict> Items
{
get
{
return new ObservableCollection<Dict>()
{
new Dict(){ Name = "Name1", Code = "Code1" } ,
new Dict(){ Name = "Name2", Code = "Code2" }
};
}
}
public CodesClass Codes { get; set; }
}
public class Dict : IDict
{
public string Name { get; set; }
public string Code { get; set; }
}
public class CodesClass
{
public Dictionary<string, object> _codes;
public CodesClass()
{
_codes = new Dictionary<string, object>();
}
public object this[string param]
{
get
{
if (_codes.ContainsKey(param))
return _codes[param];
else
return null;// "I have no " + param;
}
set
{
_codes[param] = value;
}
}
}
}
When I run app and select all 4 comboboxes and Press button, I can see that twoway binding in one combobox(Custom Control declared in template ) do not work
---------------------------
---------------------------
STANDARD_XAML=Code2;STANDARD_TEMPLATE=Code2;MYCONTROL_XAML=Code2
---------------------------
ОК
---------------------------
Some code from control
public static readonly DependencyProperty PCValueProperty =
DependencyProperty.Register("PCValue", typeof(string), typeof(ParamCombo),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnPCValuePropertyChanged)));
//new PropertyMetadata(new PropertyChangedCallback(OnValuePropertyChanged)));, new PropertyChangedCallback(OnPCValuePropertyChanged))
#endregion
private static void OnPCValuePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
ParamCombo paramCombo = (ParamCombo)sender;
paramCombo.UpdateSelected((e.NewValue == null) ? "" : e.NewValue.ToString());
}
Thanks for your help!
I have had problems with twoway binding in a combo in a customcontrol template and the solution was to override OnApplyTemplate in the custom control, using Template.FindName to get the combo, get the DataContex object of the combo and raise PropertyChanged in the DataContext object for the bound property. My problem was to update the combo when the window was loaded.

WPF - Bind between two CheckBoxes' Content with a Label.Content in two different windows

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();
}
}

Extending TreeView with Extra Properties?

I'm working on adding some properties to an extension class of TreeView. I need the extra fields for context when one of the items in the tree is clicked. I can't seem to get the tree view to show any of the data I'm giving it.
In my MainView.cs I'm simply setting the items source as such:
TreeMenu.ItemsSource = (an ObservableCollection of ParentItems)
XAML:
<Grid x:Name="TreeGrid" Width="350" HorizontalAlignment="Left">
<TreeView Name="TreeMenu" Background="Red" Foreground="Black">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type model:ParentItem}" ItemsSource="{Binding ChildItems}">
<TextBlock Text="{Binding Text}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
Object model:
public class ParentItem : TreeViewItem, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string info)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
}
public ParentItem()
{
_text = "";
_url = "";
_childItems = new ObservableCollection<ChildItem>();
}
private string _text;
public string Text
{
get
{
return _text;
}
set
{
_text = value;
NotifyPropertyChanged("Text");
}
}
private string _url;
public string URL
{
get
{
return _url;
}
set
{
_url = value;
NotifyPropertyChanged("URL");
}
}
private ObservableCollection<ChildItem> _childItems;
public ObservableCollection<ChildItem> ChildItems
{
get
{
return _childItems;
}
set
{
_childItems = value;
NotifyPropertyChanged("ChildItems");
}
}
}
Note that ChildItem is almost identical to ParentItem, minus the collection object. Originally I tried extending TreeNode in my object classes, but that had the same issue.
Does anyone know why my TreeView won't appear? Am I missing something while extending TreeView?
No point in extending TreeViewItem.
We don't see how you assign your collection so they might something done wrongly.
This does work:
Code
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ItemCollection
{
new Item
{
Text = "A",
Items = new ItemCollection
{
new Item
{
Text = "B",
Items = new ItemCollection
{
new Item
{
Text = "C"
}
}
}
}
}
};
}
}
public class Item
{
public string Text { get; set; }
public ItemCollection Items { get; set; }
}
public class ItemCollection : ObservableCollection<Item>
{
}
}
XAML
<Window x:Class="WpfApplication4.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-namespace:WpfApplication4"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TreeView ItemsSource="{Binding}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="local:Item" ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Text}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
Result

WPF Add items to observable collection and print. Returning object reference error

I have a simple app here that uses an observable collection and generates tabcontrol tabs per item. However when I try to add additional tabs it fails. I also noticed when i attempt to print the data in the collection, it appears i can not do that. I get the following error for both lines of code.
Error 1 An object reference is required for the non-static field,
method, or property
InitializeComponent();
//ERRORS on both lines below
Console.WriteLine(ViewModel.TabItems);
ViewModel.AddContentItem();
MainWindow.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//ERRORS on both lines below
Console.WriteLine(ViewModel.TabItems);
ViewModel.AddContentItem();
}
}
}
MainWindow.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:data="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="250">
<Window.DataContext>
<data:ViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TabControl ItemsSource="{Binding TabItems}" Grid.Row="1" Background="LightBlue">
<TabControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="{Binding Header}" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Content}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
</Window>
ViewModel.cs
using System;
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApplication1
{
public class ViewModel : ObservableObject
{
private ObservableCollection<TabItem> tabItems;
public ObservableCollection<TabItem> TabItems
{
get { return tabItems ?? (tabItems = new ObservableCollection<TabItem>()); }
}
public ViewModel()
{
TabItems.Add(new TabItem { Header = "One", Content = DateTime.Now.ToLongDateString() });
TabItems.Add(new TabItem { Header = "Two", Content = DateTime.Now.ToLongDateString() });
TabItems.Add(new TabItem { Header = "Three", Content = DateTime.Now.ToLongDateString() });
}
public void AddContentItem()
{
TabItems.Add(new TabItem { Header = "Three", Content = DateTime.Now.ToLongDateString() });
}
}
public class TabItem
{
public string Header { get; set; }
public string Content { get; set; }
}
}
ObservableObject.cs
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WpfApplication1
{
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
You should do this instead
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var viewModel = (ViewModel) this.DataContext;
Debug.WriteLine(viewModel.TabItems);
viewModel.AddContentItem();
}
}
}
Updated thanks King King

Bound treeview partially refreshing

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
}

Categories

Resources