How to get CaretIndex value of TextBox control in the view model? - c#

Since CaretIndex of TextBox control is not a DependencyProperty, how do I get the value of CaretIndex in the ViewModel?

You can you Interaction.Behaviors create your own behaviour and get the property you want from it.
For eg. this is a EventCommandConverterBehavior. Using it will return the property value which you specify from xaml, and if property name is not set. it will return Corresponding EventArgs
public class EventCommandConverterBehavior : Behavior<FrameworkElement>
{
private Delegate eventHandler;
private EventInfo oldEvent;
// Event
public string EventName { get { return (string)GetValue(EventNameProperty); } set { SetValue(EventNameProperty, value); } }
public static readonly DependencyProperty EventNameProperty = DependencyProperty.Register("EventName", typeof(string), typeof(EventCommandConverterBehavior), new PropertyMetadata(null, OnEventChanged));
// Command
public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } }
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandConverterBehavior), new PropertyMetadata(null));
public string PropertyName { get { return (string)GetValue(PropertyNameProperty); } set { SetValue(PropertyNameProperty, value); } }
public static readonly DependencyProperty PropertyNameProperty = DependencyProperty.Register("PropertyName", typeof(string), typeof(EventCommandConverterBehavior), new PropertyMetadata());
private static void OnEventChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
var behavior = (EventCommandConverterBehavior)dependencyObject;
if (behavior.AssociatedObject != null)
behavior.AttachHandler((string)args.NewValue);
}
protected override void OnAttached()
{
AttachHandler(this.EventName);
}
private void AttachHandler(string eventName)
{
// detach old event
if (this.oldEvent != null)
this.oldEvent.RemoveEventHandler(this.AssociatedObject, this.eventHandler);
// attach new event
if (string.IsNullOrEmpty(eventName))
{
return;
}
var eventInfo = this.AssociatedObject.GetType().GetEvent(eventName);
if (eventInfo != null)
{
var methodInfo = this.GetType()
.GetMethod("CommandExecuter", BindingFlags.Instance | BindingFlags.NonPublic);
this.eventHandler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, methodInfo);
eventInfo.AddEventHandler(this.AssociatedObject, this.eventHandler);
this.oldEvent = eventInfo;
}
else
throw new ArgumentException(string.Format("Type {0} does not contain event {1} definition.",
this.AssociatedObject.GetType().Name, eventName));
}
private void CommandExecuter(object sender, EventArgs e)
{
object parameter = null != PropertyName ? GetPropValue(sender, PropertyName) : e;
if (this.Command != null)
{
if (this.Command.CanExecute(parameter))
this.Command.Execute(parameter);
}
}
public static object GetPropValue(object src, string propName)
{
var propertyInfo = src.GetType().GetProperty(propName);
return propertyInfo != null ? propertyInfo.GetValue(src, null) : null;
}
}
In Xaml you have to write
<TextBox Name="TextBox1" Text="SomeText" Height="20" Width="60">
<i:Interaction.Behaviors >
<wpfPractice:EventCommandConverterBehavior Command="{Binding PropertyValueCommand}" EventName="SelectionChanged" PropertyName="CaretIndex" />
</i:Interaction.Behaviors>
</TextBox>
Where PropertyValueCommand shold be a command in DataContext(i.e. ViewModel.
let me know if it works.

Related

WPF ComboBox Not updating on propertychanged event

I have a custom combobox in my WPF application and the combo box is not updating when my item source is updated after initial launch. The itemsSource is a custom observableDictionary. I've implemented INotifyPropertyChanged on my properties with my observableDictionary but it won't update. I've searched through every WPF propertychanged event not working on stack overflow and i'm looking for some assistance.
Custom Combobox Code:
<controls:MultiSelectComboBox Width="100" Height="30" Padding="0 10 0 0" Grid.Row="0" Grid.Column="1"
ItemsSource="{Binding Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True,
Path=DataContext.OptionTeamMembersDictionary,
BindsDirectlyToSource=True,
RelativeSource={RelativeSource AncestorType={x:Type UserControl},Mode=FindAncestor}}"
SelectedItems="{Binding SelectedOptionTeamMembersDictionary, Mode=TwoWay}"
x:Name="TeamMemberDisplay"
ToolTip="{Binding Path=Text, RelativeSource={RelativeSource Self}}"/>
Properties and private variables:
private ObservableDictionary<string, object> _optionTeamMembersDictionary;
private ObservableDictionary<string, object> _selectedOptionTeamMembersDictionary;
public ObservableDictionary<string, object> OptionTeamMembersDictionary
{
get
{
return _optionTeamMembersDictionary;
}
set
{
_optionTeamMembersDictionary = value;
OnPropertyChanged("OptionTeamMembersDictionary");
}
}
public ObservableDictionary<string, object> SelectedOptionTeamMembersDictionary
{
get
{
return _selectedOptionTeamMembersDictionary;
}
set
{
_selectedOptionTeamMembersDictionary = value;
OnPropertyChanged("SelectedOptionTeamMembersDictionary");
}
}
I use a button to trigger a database pull which leads each row into an object and then populates the optionTeamMemberDictionary when it returns more then one row of data.
All of the above works when the data is loaded in my constructor but when its loaded after launch my comboboxes do not show the new data in the collection.
EDIT:
Code for the Custom ComboBox being used:
https://www.codeproject.com/Articles/563862/Multi-Select-ComboBox-in-WPF is the URL this came from. Some edits were made to implement an obserableDirctionary instead of normal dictionary
public partial class MultiSelectComboBox : UserControl
{
private ObservableCollection<Node> _nodeList;
public MultiSelectComboBox()
{
InitializeComponent();
_nodeList = new ObservableCollection<Node>();
}
#region Dependency Properties
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(ObservableDictionary<string, object>), typeof(MultiSelectComboBox), new FrameworkPropertyMetadata(null,
new PropertyChangedCallback(MultiSelectComboBox.OnItemsSourceChanged)));
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems", typeof(ObservableDictionary<string, object>), typeof(MultiSelectComboBox), new FrameworkPropertyMetadata(null,
new PropertyChangedCallback(MultiSelectComboBox.OnSelectedItemsChanged)));
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MultiSelectComboBox), new UIPropertyMetadata(string.Empty));
public static readonly DependencyProperty DefaultTextProperty =
DependencyProperty.Register("DefaultText", typeof(string), typeof(MultiSelectComboBox), new UIPropertyMetadata(string.Empty));
public ObservableDictionary<string, object> ItemsSource
{
get { return (ObservableDictionary<string, object>)GetValue(ItemsSourceProperty); }
set
{
SetValue(ItemsSourceProperty, value);
}
}
public ObservableDictionary<string, object> SelectedItems
{
get { return (ObservableDictionary<string, object>)GetValue(SelectedItemsProperty); }
set
{
SetValue(SelectedItemsProperty, value);
}
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public string DefaultText
{
get { return (string)GetValue(DefaultTextProperty); }
set { SetValue(DefaultTextProperty, value); }
}
#endregion
#region Events
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MultiSelectComboBox control = (MultiSelectComboBox)d;
control.DisplayInControl();
}
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MultiSelectComboBox control = (MultiSelectComboBox)d;
control.SelectNodes();
control.SetText();
}
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
CheckBox clickedBox = (CheckBox)sender;
if (clickedBox.Content == "All")
{
if (clickedBox.IsChecked.Value)
{
foreach (Node node in _nodeList)
{
node.IsSelected = true;
}
}
else
{
foreach (Node node in _nodeList)
{
node.IsSelected = false;
}
}
}
else
{
int _selectedCount = 0;
foreach (Node s in _nodeList)
{
if (s.IsSelected && s.Title != "All")
_selectedCount++;
}
if (_selectedCount == _nodeList.Count - 1)
_nodeList.FirstOrDefault(i => i.Title == "All").IsSelected = true;
else
_nodeList.FirstOrDefault(i => i.Title == "All").IsSelected = false;
}
SetSelectedItems();
SetText();
}
#endregion
#region Methods
private void SelectNodes()
{
foreach (KeyValuePair<string, object> keyValue in SelectedItems)
{
Node node = _nodeList.FirstOrDefault(i => i.Title == keyValue.Key);
if (node != null)
node.IsSelected = true;
}
}
private void SetSelectedItems()
{
if (SelectedItems == null)
SelectedItems = new ObservableDictionary<string, object>();
SelectedItems.Clear();
foreach (Node node in _nodeList)
{
if (node.IsSelected && node.Title != "All")
{
if (this.ItemsSource.Count > 0)
SelectedItems.Add(node.Title, this.ItemsSource[node.Title]);
}
}
}
private void DisplayInControl()
{
_nodeList.Clear();
if (this.ItemsSource.Count > 0)
_nodeList.Add(new Node("All"));
foreach (KeyValuePair<string, object> keyValue in this.ItemsSource)
{
Node node = new Node(keyValue.Key);
_nodeList.Add(node);
}
MultiSelectCombo.ItemsSource = _nodeList;
}
private void SetText()
{
if (this.SelectedItems != null)
{
StringBuilder displayText = new StringBuilder();
foreach (Node s in _nodeList)
{
if (s.IsSelected == true && s.Title == "All")
{
displayText = new StringBuilder();
displayText.Append("All");
break;
}
else if (s.IsSelected == true && s.Title != "All")
{
displayText.Append(s.Title);
displayText.Append(',');
}
}
this.Text = displayText.ToString().TrimEnd(new char[] { ',' });
}
// set DefaultText if nothing else selected
if (string.IsNullOrEmpty(this.Text))
{
this.Text = this.DefaultText;
}
}
#endregion
}
public class Node : INotifyPropertyChanged
{
private string _title;
private bool _isSelected;
#region ctor
public Node(string title)
{
Title = title;
}
#endregion
#region Properties
public string Title
{
get
{
return _title;
}
set
{
_title = value;
NotifyPropertyChanged("Title");
}
}
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
NotifyPropertyChanged("IsSelected");
}
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
After much troubleshooting i was able to figure out an answer for this. onItemsSourceChanged was not firing after the control was instantiated so it never got updates made after initial launch of the application. I edited the OnItemsSourceChanged Function on the MultiFunctionComboBox to the below so it would fire on a changed event and it is working as expected now.
private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MultiSelectComboBox control = (MultiSelectComboBox)d;
var action = new NotifyCollectionChangedEventHandler(
(o, args) =>
{
MultiSelectComboBox c = (MultiSelectComboBox)d;
c?.DisplayInControl();
});
if (e.OldValue != null)
{
var sourceCollection = (ObservableDictionary<string, object>)e.OldValue;
sourceCollection.CollectionChanged -= action;
}
if (e.NewValue != null)
{
var sourceCollection = (ObservableDictionary<string, object>)e.NewValue;
sourceCollection.CollectionChanged += action;
}
control.DisplayInControl();
}

why my SelectedItems dependency property always returns null to bound property

I created a UserControl1 that wraps a DataGrid (this is simplified for test purposes, the real scenario involves a third-party control but the issue is the same). The UserControl1 is used in the MainWindow of the test app like so:
<test:UserControl1 ItemsSource="{Binding People,Mode=OneWay,ElementName=Self}"
SelectedItems="{Binding SelectedPeople, Mode=TwoWay, ElementName=Self}"/>
Everything works as expected except that when a row is selected in the DataGrid, the SelectedPeople property is always set to null.
The row selection flow is roughly: UserControl1.DataGrid -> UserControl1.DataGrid_OnSelectionChanged -> UserControl1.SelectedItems -> MainWindow.SelectedPeople
Debugging shows the IList with the selected item from the DataGrid is being passed to the SetValue call of the SelectedItems dependency property. But when the SelectedPeople setter is subsequently called (as part of the binding process) the value passed to it is always null.
Here's the relevant UserControl1 XAML:
<Grid>
<DataGrid x:Name="dataGrid" SelectionChanged="DataGrid_OnSelectionChanged" />
</Grid>
In the code-behind of UserControl1 are the following definitions for the SelectedItems dependency properties and the DataGrid SelectionChanged handler:
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(IList), typeof(UserControl1), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemsChanged));
public IList SelectedItems
{
get { return (IList)GetValue(SelectedItemsProperty); }
set
{
SetValue(SelectedItemsProperty, value);
}
}
private bool _isUpdatingSelectedItems;
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctrl = d as UserControl1;
if ((ctrl != null) && !ctrl._isUpdatingSelectedItems)
{
ctrl._isUpdatingSelectedItems = true;
try
{
ctrl.dataGrid.SelectedItems.Clear();
var selectedItems = e.NewValue as IList;
if (selectedItems != null)
{
var validSelectedItems = selectedItems.Cast<object>().Where(item => ctrl.ItemsSource.Contains(item) && !ctrl.dataGrid.SelectedItems.Contains(item)).ToList();
validSelectedItems.ForEach(item => ctrl.dataGrid.SelectedItems.Add(item));
}
}
finally
{
ctrl._isUpdatingSelectedItems = false;
}
}
}
private void DataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!_isUpdatingSelectedItems && sender is DataGrid)
{
_isUpdatingSelectedItems = true;
try
{
var x = dataGrid.SelectedItems;
SelectedItems = new List<object>(x.Cast<object>());
}
finally
{
_isUpdatingSelectedItems = false;
}
}
}
Here is definition of SomePeople from MainWindow code-behind:
private ObservableCollection<Person> _selectedPeople;
public ObservableCollection<Person> SelectedPeople
{
get { return _selectedPeople; }
set { SetProperty(ref _selectedPeople, value); }
}
public class Person
{
public Person(string first, string last)
{
First = first;
Last = last;
}
public string First { get; set; }
public string Last { get; set; }
}
I faced the same problem, i dont know reason, but i resolved it like this:
1) DP
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(object), typeof(UserControl1),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemsChanged));
public object SelectedItems
{
get { return (object) GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
2) Grid event
private void DataGrid_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var SelectedItemsCasted = SelectedItems as IList<object>;
if (SelectedItemsCasted == null)
return;
foreach (object addedItem in e.AddedItems)
{
SelectedItemsCasted.Add(addedItem);
}
foreach (object removedItem in e.RemovedItems)
{
SelectedItemsCasted.Remove(removedItem);
}
}
3) In UC which contain UserControl1
Property:
public IList<object> SelectedPeople { get; set; }
Constructor:
public MainViewModel()
{
SelectedPeople = new List<object>();
}
I know this is a super old post- but after digging through this, and a few other posts which address this issue, I couldn't find a complete working solution. So with the concept from this post I am doing that.
I've also created a GitHub repo with the complete demo project which contains more comments and explanation of the logic than this post. MultiSelectDemo
I was able to create an AttachedProperty (with some AttachedBehavour logic as well to set up the SelectionChanged handler).
MultipleSelectedItemsBehaviour
public class MultipleSelectedItemsBehaviour
{
public static readonly DependencyProperty MultipleSelectedItemsProperty =
DependencyProperty.RegisterAttached("MultipleSelectedItems", typeof(IList), typeof(MultipleSelectedItemsBehaviour),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, MultipleSelectedItemsChangedCallback));
public static IList GetMultipleSelectedItems(DependencyObject d) => (IList)d.GetValue(MultipleSelectedItemsProperty);
public static void SetMultipleSelectedItems(DependencyObject d, IList value) => d.SetValue(MultipleSelectedItemsProperty, value);
public static void MultipleSelectedItemsChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
{
if (sender is DataGrid dataGrid)
{
if (e.NewValue == null)
{
dataGrid.SelectionChanged -= DataGrid_SelectionChanged;
}
else
{
dataGrid.SelectionChanged += DataGrid_SelectionChanged;
}
}
}
private static void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is DataGrid dataGrid)
{
var selectedItems = GetMultipleSelectedItems(dataGrid);
if (selectedItems == null) return;
foreach (var item in e.AddedItems)
{
try
{
selectedItems.Add(item);
}
catch (ArgumentException)
{
}
}
foreach (var item in e.RemovedItems)
{
selectedItems.Remove(item);
}
}
}
}
To use it, one critical thing within the view model, is that the view model collection must be initialized so that the attached property/behaviour sets up the SelectionChanged handler. In this example I've done that in the VM constructor.
public MainWindowViewModel()
{
MySelectedItems = new ObservableCollection<MyItem>();
}
private ObservableCollection<MyItem> _myItems;
public ObservableCollection<MyItem> MyItems
{
get => _myItems;
set => Set(ref _myItems, value);
}
private ObservableCollection<MyItem> _mySelectedItems;
public ObservableCollection<MyItem> MySelectedItems
{
get => _mySelectedItems;
set
{
// Remove existing handler if there is already an assignment made (aka the property is not null).
if (MySelectedItems != null)
{
MySelectedItems.CollectionChanged -= MySelectedItems_CollectionChanged;
}
Set(ref _mySelectedItems, value);
// Assign the collection changed handler if you need to know when items were added/removed from the collection.
if (MySelectedItems != null)
{
MySelectedItems.CollectionChanged += MySelectedItems_CollectionChanged;
}
}
}
private int _selectionCount;
public int SelectionCount
{
get => _selectionCount;
set => Set(ref _selectionCount, value);
}
private void MySelectedItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Do whatever you want once the items are added or removed.
SelectionCount = MySelectedItems != null ? MySelectedItems.Count : 0;
}
And finally to use it in the XAML
<DataGrid Grid.Row="0"
ItemsSource="{Binding MyItems}"
local:MultipleSelectedItemsBehaviour.MultipleSelectedItems="{Binding MySelectedItems}" >
</DataGrid>

WPF: Implement ICommandSource Without Breaking IsEnabled

I have created a TextBox that implements ICommandSource, for the most part I followed Microsoft's example using a Slider. This TextBox will execute the bound command upon pressing the "Enter" key. This portion of the behavior is working correctly, the issue I am having is that IsEnabled can no longer be set in XAML? I am not sure why this is, you can still set IsEnabled on native Microsoft classes like Button.
public class CommandTextBox : TextBox, ICommandSource
{
// The DependencyProperty for the Command.
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandTextBox), new PropertyMetadata(OnCommandChanged));
// The DependencyProperty for the CommandParameter.
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(CommandTextBox));
// The DependencyProperty for the CommandTarget.
public static readonly DependencyProperty CommandTargetProperty = DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(CommandTextBox));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public bool CommandResetsText { get; set; }
public IInputElement CommandTarget
{
get { return (IInputElement)GetValue(CommandTargetProperty); }
set { SetValue(CommandTargetProperty, value); }
}
// Command dependency property change callback.
private static void OnCommandChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
CommandTextBox ctb = (CommandTextBox)dp;
ctb.HookUpCommand((ICommand)e.OldValue, (ICommand)e.NewValue);
}
// Add a new command to the Command Property.
private void HookUpCommand(ICommand oldCommand, ICommand newCommand)
{
// If oldCommand is not null, then we need to remove the handlers.
if (oldCommand != null)
RemoveCommand(oldCommand);
AddCommand(newCommand);
}
// Remove an old command from the Command Property.
private void RemoveCommand(ICommand command)
{
EventHandler handler = CanExecuteChanged;
command.CanExecuteChanged -= handler;
}
// Add the command.
private void AddCommand(ICommand command)
{
var handler = new EventHandler(CanExecuteChanged);
canExecuteChangedHandler = handler;
if (command != null)
command.CanExecuteChanged += canExecuteChangedHandler;
}
private void CanExecuteChanged(object sender, EventArgs e)
{
if (Command != null)
{
RoutedCommand command = Command as RoutedCommand;
// If a RoutedCommand.
if (command != null)
{
if (command.CanExecute(CommandParameter, CommandTarget))
this.IsEnabled = true;
else
this.IsEnabled = false;
}
// If a not RoutedCommand.
else
{
if (Command.CanExecute(CommandParameter))
this.IsEnabled = true;
else
this.IsEnabled = false;
}
}
}
// If Command is defined, pressing the enter key will invoke the command;
// Otherwise, the textbox will behave normally.
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Key == Key.Enter)
{
if (Command != null)
{
RoutedCommand command = Command as RoutedCommand;
if (command != null)
command.Execute(CommandParameter, CommandTarget);
else
Command.Execute(CommandParameter);
if (CommandResetsText)
this.Text = String.Empty;
}
}
}
private EventHandler canExecuteChangedHandler;
}
XAML
<Button Command="{Binding GenericCommand}" IsEnabled="False" /> // This is disabled(desired).
<CommandTextBox Command="{Binding GenericCommand}" IsEnabled="False" /> // This is enabled?
Any feedback would be appreciated.
First, you need to create a private property or a field that will be set if the command can execute:
private bool _canExecute;
Second, you need to override IsEnabledCore property:
protected override bool IsEnabledCore
{
get
{
return ( base.IsEnabledCore && _canExecute );
}
}
And finally, you just fixing CanExecuteChanged method by replacing IsEnabled with _canExecute and coercing IsEnabledCore after all:
private void CanExecuteChanged(object sender, EventArgs e)
{
if (Command != null)
{
RoutedCommand command = Command as RoutedCommand;
// If a RoutedCommand.
if (command != null)
{
_canExecute = command.CanExecute(CommandParameter, CommandTarget);
}
// If a not RoutedCommand.
else
{
_canExecute = Command.CanExecute(CommandParameter);
}
}
CoerceValue(UIElement.IsEnabledProperty);
}

How to define an extend stackpanel control with two child dependency properties

I have to write an ExtendedStackPanel control which will have two dependency properties like this.
<ExtendedStackPanel IsReadOnly="{Binding Item.IsReadOnly, Mode=OneWay}" >
<TemplateTrue>
... control visible when isreadonly is true
</TemplateTrue>
<TemplateFalse>
... control visible when isreadonly is false
</TemplateFalse>
</ExtendedStackPanel>
I've written this to achieve the goal but it's not working.
public class ExtendedStackPanel : StackPanel
{
public ExtendedStackPanel()
: base()
{
this.Orientation = System.Windows.Controls.Orientation.Vertical;
}
#region IsReadOnly
public bool IsReadOnly
{
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
public static readonly DependencyProperty IsReadOnlyProperty =
DependencyProperty.Register("IsReadOnly", typeof(bool),
typeof(ExtendedStackPanel), new PropertyMetadata(new PropertyChangedCallback(OnReadOnlyChanged)));
static void OnReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var visible = (bool)e.NewValue;
var control = d as ExtendedStackPanel;
if (visible)
{
control.TemplateTrue.Visibility = Visibility.Visible;
control.TemplateFalse.Visibility = Visibility.Collapsed;
}
else
{
control.TemplateTrue.Visibility = Visibility.Collapsed;
control.TemplateFalse.Visibility = Visibility.Visible;
}
}
#endregion
#region TemplateTrue
public Control TemplateTrue
{
get { return (Control)GetValue(TemplateTrueProperty); }
set { SetValue(TemplateTrueProperty, value); }
}
public static readonly DependencyProperty TemplateTrueProperty =
DependencyProperty.Register("TemplateTrue", typeof(Control),
typeof(ExtendedStackPanel), new PropertyMetadata(new PropertyChangedCallback(OnTemplateTrueChanged)));
static void OnTemplateTrueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as ExtendedStackPanel;
control.TemplateTrue.Visibility = control.IsReadOnly ? Visibility.Visible : Visibility.Collapsed;
}
#endregion
#region TemplateFalse
public Control TemplateFalse
{
get { return (Control)GetValue(TemplateFalseProperty); }
set { SetValue(TemplateFalseProperty, value); }
}
public static readonly DependencyProperty TemplateFalseProperty =
DependencyProperty.Register("TemplateFalse", typeof(Control),
typeof(ExtendedStackPanel), new PropertyMetadata(new PropertyChangedCallback(OnTemplateFalseChanged)));
static void OnTemplateFalseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as ExtendedStackPanel;
control.TemplateFalse.Visibility = !control.IsReadOnly ? Visibility.Visible : Visibility.Collapsed;
}
#endregion
}
In my code, I have put a combobox control when IsReadOnly is set to false, and a simple textbox when IsReadOnly is set to true but nothing is displayed when code is run.
Help me please.
Finally, I choose to use a UserControl, in which I put two ContentControl.
In code behind of the UserControl, I write this:
public partial class ConditionalControl : UserControl, INotifyPropertyChanged
{
public ConditionalControl()
{
InitializeComponent();
this.IsReadOnly = false;
}
#region IsReadOnly
public bool IsReadOnly
{
get { return (bool)GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
public static readonly DependencyProperty IsReadOnlyProperty =
DependencyProperty.Register("IsReadOnly", typeof(bool),
typeof(ConditionalControl), new PropertyMetadata(new PropertyChangedCallback(OnReadOnlyChanged)));
static void OnReadOnlyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var visible = (bool)e.NewValue;
var control = d as ConditionalControl;
if (visible)
{
control.TemplateTrueContent.Visibility = Visibility.Visible;
control.TemplateFalseContent.Visibility = Visibility.Collapsed;
}
else
{
control.TemplateTrueContent.Visibility = Visibility.Collapsed;
control.TemplateFalseContent.Visibility = Visibility.Visible;
}
}
#endregion
#region TemplateFalse
public object TemplateFalse
{
get { return (object)GetValue(TemplateFalseProperty); }
set { SetValue(TemplateFalseProperty, value); }
}
public static readonly DependencyProperty TemplateFalseProperty =
DependencyProperty.Register("TemplateFalse", typeof(object),
typeof(ConditionalControl), new PropertyMetadata(new PropertyChangedCallback(OnTemplateFalseChanged)));
static void OnTemplateFalseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as ConditionalControl;
control.TemplateFalseContent.Visibility = !control.IsReadOnly ? Visibility.Visible : Visibility.Collapsed;
control.OnPropertyChanged("TemplateFalse");
}
#endregion
#region TemplateTrue
public object TemplateTrue
{
get { return (object)GetValue(TemplateTrueProperty); }
set { SetValue(TemplateTrueProperty, value); }
}
public static readonly DependencyProperty TemplateTrueProperty =
DependencyProperty.Register("TemplateTrue", typeof(object),
typeof(ConditionalControl), new PropertyMetadata(new PropertyChangedCallback(OnTemplateTrueChanged)));
static void OnTemplateTrueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = d as ConditionalControl;
control.TemplateTrueContent.Visibility = control.IsReadOnly ? Visibility.Visible : Visibility.Collapsed;
control.OnPropertyChanged("TemplateTrue");
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (propertyName == "TemplateFalse")
{
this.TemplateFalseContent.Content = this.TemplateFalse;
}
if (propertyName == "TemplateTrue")
{
this.TemplateTrueContent.Content = this.TemplateTrue;
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Hope this will help someone.

Button Command get not fired

I have a strange situation.
I working on an App for WINRT and have some problems with a command binding. This is the part of the xaml:
<control:ItemsHub ItemsSource="{Binding Categories}">
<control:ItemsHub.SectionHeaderTemplate>
<DataTemplate>
<Button Command="{Binding CategoryNavigationCommand}" Margin="5,0,0,10" Content="{Binding Header}"/>
</DataTemplate>
</control:ItemsHub.SectionHeaderTemplate>
</control:ItemsHub>
This is my ViewModel:
public CategorySectionViewModel(IRecipeService recipeService, INavigationService navigationService, RecipeTreeItemDto treeItem)
{
...
CategoryNavigationCommand = new DelegateCommand(NavigateToCategory);
...
}
private string _header;
public string Header
{
get { return _header; }
set { SetProperty(ref _header, value); }
}
public DelegateCommand CategoryNavigationCommand { get; private set; }
private void NavigateToCategory()
{
_navigationService.Navigate("CategoryHub", _recipeTreeItemDto.NodePath);
}
I don't get any binding errors in the output window and also the "Header" gets shown in the Button. But the Command won't get fired wenn i click on it! What i'm doing wrong?
Maybe it is because i created a custom HubControl. With this control i'm able to attach an ItemSource and ItemTemplate for the HubSection-Header and the HubSection-Content. Maybe because of this some bindings getting lost?
Here is my custom hub control:
public class ItemsHub : Hub
{
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
public IList ItemsSource
{
get { return (IList)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public HubSection SpotlightSection
{
get { return (HubSection)GetValue(SpotlightSectionProperty); }
set { SetValue(SpotlightSectionProperty, value); }
}
public DataTemplate SectionHeaderTemplate
{
get { return (DataTemplate)GetValue(SectionHeaderTemplateProperty); }
set { SetValue(SectionHeaderTemplateProperty, value); }
}
public static readonly DependencyProperty ItemTemplateProperty =
DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(ItemsHub), new PropertyMetadata(null, ItemTemplateChanged));
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IList), typeof(ItemsHub), new PropertyMetadata(null, ItemsSourceChanged));
public static readonly DependencyProperty SpotlightSectionProperty =
DependencyProperty.Register("SpotlightSection", typeof(HubSection), typeof(ItemsHub), new PropertyMetadata(default(HubSection), SpotlightSectionChanged));
public static readonly DependencyProperty SectionHeaderTemplateProperty =
DependencyProperty.Register("SectionHeaderTemplate", typeof(DataTemplate), typeof(ItemsHub), new PropertyMetadata(default(DataTemplate), HeaderTemplateChanged));
private static void SpotlightSectionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsHub hub = d as ItemsHub;
if (hub != null)
{
bool hubContainsSpotLight = hub.Sections.Contains(hub.SpotlightSection);
if (hub.SpotlightSection != null && !hubContainsSpotLight)
{
hub.Sections.Add(hub.SpotlightSection);
}
if (hub.SpotlightSection == null && hubContainsSpotLight)
{
hub.Sections.Remove(hub.SpotlightSection);
}
}
}
private static void HeaderTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsHub hub = d as ItemsHub;
if (hub != null)
{
DataTemplate template = e.NewValue as DataTemplate;
if (template != null)
{
// Apply template
foreach (var section in hub.Sections.Except(new List<HubSection> { hub.SpotlightSection }))
{
section.HeaderTemplate = template;
}
}
}
}
private static void ItemTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsHub hub = d as ItemsHub;
if (hub != null)
{
DataTemplate template = e.NewValue as DataTemplate;
if (template != null)
{
// Apply template
foreach (var section in hub.Sections.Except(new List<HubSection> { hub.SpotlightSection }))
{
section.ContentTemplate = template;
}
}
}
}
private static void ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsHub hub = d as ItemsHub;
if (hub != null)
{
IList items = e.NewValue as IList;
if (items != null)
{
var spotLightSection = hub.SpotlightSection;
hub.Sections.Clear();
if (spotLightSection != null)
{
hub.Sections.Add(spotLightSection);
}
foreach (var item in items)
{
HubSection section = new HubSection();
section.DataContext = item;
section.Header = item;
DataTemplate headerTemplate = hub.SectionHeaderTemplate;
section.HeaderTemplate = headerTemplate;
DataTemplate contentTemplate = hub.ItemTemplate;
section.ContentTemplate = contentTemplate;
hub.Sections.Add(section);
}
}
}
}
}
Thanks for your help!
I found the solution! I don't know why but the section header of a hub control is not interactive by default! So i have to set the interactivity to true when i assign the itemsource in my custom ItemHub-Control.
Here is what i changed in the ItemsHub Control:
private static void ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ItemsHub hub = d as ItemsHub;
if (hub != null)
{
IList items = e.NewValue as IList;
if (items != null)
{
var spotLightSection = hub.SpotlightSection;
hub.Sections.Clear();
if (spotLightSection != null)
{
hub.Sections.Add(spotLightSection);
}
foreach (var item in items)
{
HubSection section = new HubSection();
DataTemplate headerTemplate = hub.SectionHeaderTemplate;
section.HeaderTemplate = headerTemplate;
DataTemplate contentTemplate = hub.ItemTemplate;
section.ContentTemplate = contentTemplate;
section.DataContext = item;
section.Header = item;
//This line fixed my problem.
section.IsHeaderInteractive = true;
hub.Sections.Add(section);
}
}
}
You can use following binding expression
Command="{Binding CategoryNavigationCommand,RelativeSource={RelativeSource AncestorType=XYX}}"
and XYZ is a control type in which you have placed ItemsHub

Categories