WPF how to force menu item bindings to update when menu opens - wpf

I have a value that can change that doesn't raise a change event and the menu item bound to the value doesn't correctly reflect the state when the menu item is opened. I'd like to update this binding when the menu opens. How do I do this?
Can I have a menu item that just polls it's bindings each time the menu is opened? In this case the IsCommEnabled property:
<MenuItem Header="{Binding EnableComm}"
Command="{Binding Root.ToggleCommunications}"
IsChecked="{Binding Authorization.IsCommEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
--
public bool IsCommEnabled {
get { return _communications.IsCommEnabled; }
}

You can subscribe to the SubmenuOpened event, and manually update the binding:
void MenuItem_SubmenuOpened(object sender, RoutedEventArgs e)
{
((MenuItem)sender).GetBindingExpression(MenuItem.IsCheckedProperty).UpdateTarget();
}
Please note that the above applies to the Parent item being opened, so you may need to wrangle it a bit to ensure that it is the right item that is getting updated. You can use the Items collection on the MenuItem to dig deeper.

You have to raise NotifyPropertyChanged if you want to push the IsCommEnabled back to the bound Dependency Property

Related

WPF ComboBox SelectionChanged event firing twice

In my DataGrid I am using DataGridComboBoxColumn as follows. Its SelectionChanged event (defined below) always fires twice - once when I click on an item, and then again when I select the new item from the dropdown. When I click on the item that I want to change the SelectionChanged event fires and shows the old value, and then when I select on a new value it fires again and correctly show the new value. But I want the event to be fired only when I select a new value for the combobox.
Question: What is causing this behavior and how can the issue be fixed?
Remark: Many users online seem to have similar issues posted here but none of them helped resolve my issue - maybe, the context is a bit different here. Moreover, the XAML and the code seem ok as it correctly displays the combobox values along with the correctly combox selected values for each row in the grid. Plus, the SelectionChanged event does correctly show the newly selected value but when it fires the second time. Similar code is shown here.
<DataGridComboBoxColumn Header="StartTime" SelectedItemBinding="{Binding localTime}" ItemsSource="{StaticResource localTimeList}">
<DataGridComboBoxColumn.EditingElementStyle>
<Style TargetType="ComboBox">
<EventSetter Event="SelectionChanged" Handler="MyComboBoxColumn_SelectionChanged"/>
</Style>
</DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>
The event:
private void MyComboBoxColumn_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
var selectedVal = comboBox.SelectedValue.ToString();
}
What is causing this behavior?
The SelectionChanged event is raised initially when you enter the edit mode and the SelectedItem property is being bound to your source property.
How can the issue be fixed?
The easiest way to handle this is to check whether the ComboBox has been loaded and simply return from the event handler immediately if it hasn't:
private void MyComboBoxColumn_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBox comboBox = (ComboBox)sender;
if (!comboBox.IsLoaded)
return;
//handle an actual selection here...
}

WPF Bind child window context to parent

I have a static collection:
<CollectionViewSource Source="{Binding Source={x:Static Application.Current}, Path=MarketDataListeners}" x:Key="ficServerMarketDataView"></CollectionViewSource>
which is a collection of type MarketDataListener.
I have a ListView which is bound to this collection and a ContentControl which is bound to the selected item of this ListView. In the ContentControl I have a button that launches a child window (in code behind).
What Im doing is keeping track of the selected item in the main window like this:
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
_selectedItem = ((sender as ListView).SelectedValue as MarketDataContainer);
}
and then when the button in the control control is clicked i execute:
private void ShowComponentsButton_Click(object sender, RoutedEventArgs e)
{
var detailsWindow = new ComponentWindow(_selectedItem);
var button = sender as Button;
if (button == null) return;
detailsWindow.Show();
}
This is the binding of the ContentControl:
<ContentControl Name="Detail" Content="{Binding Source={StaticResource ficServerMarketDataView}}"
ContentTemplate="{StaticResource detailsFicTemplate}" VerticalAlignment="Stretch" Foreground="Black" DockPanel.Dock="Bottom" />
Is it possible to remove the code tracking the selected item just launch the child window without a parameter? The child window's Title should be a property 'Name' on the currently selected MarketDataListener. Ideally the child window would not update when the selected item changes.
Is it possible to remove the code tracking the selected item just launch the child window without a parameter?
I would strongly recommend you to show the details in the same window,
from user experience point of view it would be preferable.
you can use a page or contentControl to show the detailsWindow data.
in that case it would be easy to achieve what you are looking for, all you would have to do is bind the ContentControl.dataContext to listviewSelected item.
otherwise if you just have to by design create a new Window you could create a singelton ViewModel which would be bound to the ListViewSelected Item and each time you will open the DetailsWindow you would access this data.

How can the ViewModel request an update in the View in WPF/MVVM?

I have a dependency property on a control in my View that is bound to a field on my ViewModel. When the user clicks a menu item I want the control to update the value of that property so the ViewModel can save it in an XML file. What is the correct mechanism to have the ViewModel request that the View update that property?
Generally with MVVM controls update their bound properties (not fields) immediately as they are edited. The ViewModel is the "state", the View is just one way of seeing that state.
Your control should update the ViewModel whenever it is edited. Your ViewModel can then save it to XML when the menu command is invoked.
I had the problem that the viewmodel was not updated when clicking on a menuitem right after writing in a TextBox.
With the parameter UpdateSourceTrigger=PropertyChanged, it worked for TextBoxes:
<TextBox Grid.Column="5" Grid.Row="7" Text="{Binding SelectedPerson.Room, UpdateSourceTrigger=PropertyChanged}"></TextBox>
But unfortunately not for DatePickers...
The strange thing is that when clicking on a button instead of the menuitem, the DatePicker is updating the viewmodel.
As I don't have more time to look for a bugfix right now, I'll just change my menuitems into buttons.
Edit: the Problem is not the menuitem but the menu itself. When I move the menuitems out of the menu, it works.
Your object must implement INotifyPropertyChanged interface and your properties should look like this
private string _property;
public string Property
{
get { return _property; }
set
{
if(_property == value) return;
_property = value;
RaisePropertyChanged("Property");
}
}
so every change made to the property will be cascaded to view through the binding mechanism.
The menu item command property will be bound to a command declared in the view model and it will trigger a method on view model and set the property value. The change will be cascaded to view:
menuItem.Click -> menuItem.Command.Execute -> viewModel.method -> change the view model property -> raise property changed event -> view property changed through binding

Silverlight ListBox - Change When Selected State Occurs

I have a ListBox that is used as a navigation menu. When an item is selected, it has a state that is highlighted. I have now implemented a message box when navigating away from a page if there are unsaved changes. The problem is, the visual state of the ListBoxItem is changed to selected upon click. I need to be able to change set the state to selected from code, instead of on click.
Is there a way to override the click event so that it doesn't cause the ListBoxItem to go to the selected state? I could then do VisualStateManager.GoToState(item, "Selected", true).
If not, is there a way to create a custom visual state for the ListBoxItem?
You should interrupt routing of MouseLeftButtonDown event from your item container and set selected item from view model. For instance:
XAML
<ListBox x:Name="lb">
<ListBoxItem>
<TextBlock MouseLeftButtonDown="TextBlock_OnMouseLeftButtonDown" Text="Test"/>
</ListBoxItem>
</ListBox>
Event Handler
private void TextBlock_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
//interrups item selection
e.Handled = true;
//here you can show "Do you want navigate from?" dialog
// and if user accepts then show selected item in menu using SelectedItem or SelectedIndex
lb.SelectedIndex = 0;
}

How to pass the selectedItem of a listbox to the View Model

This is a running question that I have updated to hopefully be a little more clear.
In short what I am trying to accomplish is pass a property from a listbox selected item to the viewmodel so that this property can be used within a new query. In the code below the Listbox inherits databinding from the parent object. The listbox contains data templates (user controls) used to render out detailed results.
The issue I am having is that within the user control I have an expander which when clicked calls a command from the ViewModel. From what I can see the Listbox object is loosing it's data context so in order for the command to be called when the expander is expanded I have to explicitly set the datacontext of the expander. Doing this seems to instantiate a new view model which resets my bound property (SelectedItemsID) to null.
Is there a way to pass the selected item from the view to the viewmodel and prevent the value from being reset to null when a button calls a command from within the templated listbox item?
I realize that both Prism and MVVMLite have workarounds for this but I am not familiar with either framework so I don't know the level of complexity in cutting either of these into my project.
Can this be accomplished outside of Prism or MVVMLite?
original post follows:
Within my project I have a listbox usercontrol which contains a custom data template.
<ListBox x:Name="ResultListBox"
HorizontalAlignment="Stretch"
Background="{x:Null}"
BorderThickness="0"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding SearchResults[0].Results,
Mode=TwoWay}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectionChanged="ResultListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<dts:TypeTemplateSelector Content="{Binding}" HorizontalContentAlignment="Stretch">
<!-- CFS Template -->
<dts:TypeTemplateSelector.CFSTemplate>
<DataTemplate>
<qr:srchCFS />
</DataTemplate>
</dts:TypeTemplateSelector.CFSTemplate>
<!-- Person Template -->
<dts:TypeTemplateSelector.PersonTemplate>
<DataTemplate>
<qr:srchPerson />
</DataTemplate>
</dts:TypeTemplateSelector.PersonTemplate>
<!-- removed for brevity -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
SelectionChanged calls the following method from the code behind
private void ResultListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ListBox)sender).SelectedItem != null)
_ViewModel.SelectedItemID = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
this.NotifyPropertyChanged(_ViewModel.SelectedItemID);//binds to VM
}
Within the ViewModel I have the following property
public string SelectedItemID
{
get
{
return this._SelectedItemID;
}
set
{
if (this._SelectedItemID == value)
return;
this._SelectedItemID = value;
}
}
the listbox template contains a custom layout with an expander control. The expander control is used to display more details related to the selected item. These details (collection) are created by making a new call to my proxy. To do this with an expander control I used the Expressions InvokeCommandAction
<toolkit:Expander Height="auto"
Margin="0,0,-2,0"
Foreground="#FFFFC21C"
Header="View Details"
IsExpanded="False"
DataContext="{Binding Source={StaticResource SearchViewModelDataSource}}"
Style="{StaticResource DetailExpander}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Expanded">
<i:InvokeCommandAction Command="{Binding GetCfsResultCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
Within the ViewModel the delegate command GetCFSResultCommandExecute which is called is fairly straight forward
private void GetCfsResultCommandExecute(object parameter)
{
long IdResult;
if (long.TryParse(SelectedItemID, out IdResult))
{
this.CallForServiceResults = this._DataModel.GetCFSResults(IdResult);}
The issue I am experiencing is when selecting a listbox Item the selectionchanged event fires and the property SelectedItemID is updated with the correct id from the selected item. When I click on the expander the Command is fired but the property SelectedItemID is set to null. I have traced this with Silverlight-Spy and the events are consistent with what you would expect when the expander is clicked the listbox item loses focus, the expander (toggle) gets focus and there is a LeftMouseDownEvent but I cannot see anything happening that explains why the property is being set to null. I added the same code used in the selection changed event to a LostFocus event on the listboxt item and still received the same result.
I'd appreciate any help with understanding why the public property SelectedItemID is being set to null when the expander button which is part of the listbox control is being set to null. And of course I would REALLY appreciate any help in learning how prevent the property from being set to null and retaining the bound ID.
Update
I have attempted to remove the datacontext reference from the Expander as this was suggested to be the issue. From what I have since this is a data template item it "steps" out of the visual tree and looses reference to the datacontext of the control which is inherited from the parent object. If I attempt to set the datacontext in code for the control all bindings to properties are lost.
My next attempt was to set the datacontext for the expander control within the constructor as
private SearchViewModel _ViewModel;
public srchCFS()
{
InitializeComponent();
this.cfsExpander.DataContext = this._ViewModel;
}
This approach does not seem to work as InvokeCommandAction is never fired. This command only seems to trigger if data context is set on the expander.
thanks in advance
With this line you create a new SearchViewModelDataSource using its default constructor.
DataContext="{Binding Source={StaticResource SearchViewModelDataSource}}"
I guess this is why you find null because this is the default value for reference type.
You can resolve the issue by setting DataContext to the same instance used to the main controll (you can do it by code after all components are initialized).
Hope this help!
Edit
I don't think that binding may be lost after setting datacontext from code. I do it every time I need to share something between two or more model.
In relation to the code you've written :
private SearchViewModel _ViewModel;
public srchCFS()
{
InitializeComponent();
this.cfsExpander.DataContext = this._ViewModel;
}
Instead of using this.cfsExpander you can try to use the FindName method. Maybe this will return you the correct instance.
object item = this.FindName("expander_name");
if ((item!=null)&&(item is Expander))
{
Expander exp = item as Expander;
exp.DataContext = this._ViewModel;
}
Try if its work for you.
Of course, this._ViewModel has to expose a property of type ICommand named GetCfsResultCommand but I think this has been already done.
While this was a hacky approach I found an intermediate solution to get the listbox item value to the view model. I ended up using the selection changed event and passing the value directly to a public property wihtin my view model. Not the best approach but it resolved the issue short term
private void ResultListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (((ListBox)sender).SelectedItem != null)
_ViewModel.SelectedItemID = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
MySelectedValue = (((ListBox)sender).SelectedItem as QueryResult).ID.ToString();
this.NotifyPropertyChanged(_ViewModel.SelectedItemID);
}
For this to fire I did have to also setup a property changed handler within the view to push the change to the VM. You can disregard the MySelectedValue line as it is secondary code I have in place for testing.
For those intereted the generic property changed handler
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}

Resources