Search Results

Search found 23 results on 1 pages for 'itemcontainergenerator'.

Page 1/1 | 1 

  • Find host from ItemContainerGenerator.itemChanged Event

    - by Mohanavel
    I'm working on C# 4.0, WPF. I have three ListView, and all three control have the same ItemContainerGenerator_ItemsChanged" event. So my problem is, when ever the event triggered, i have to find the host. lst1.ItemContainerGenerator.ItemsChanged += new System.Windows.Controls.Primitives.ItemsChangedEventHandler(ItemContainerGenerator_ItemsChanged); lst2.ItemContainerGenerator.ItemsChanged += new System.Windows.Controls.Primitives.ItemsChangedEventHandler(ItemContainerGenerator_ItemsChanged); lst3.ItemContainerGenerator.ItemsChanged += new System.Windows.Controls.Primitives.ItemsChangedEventHandler(ItemContainerGenerator_ItemsChanged); void ItemContainerGenerator_ItemsChanged(object sender, System.Windows.Controls.Primitives.ItemsChangedEventArgs e) { //TODO: Find host and proceed. **REAL Problem** // ListViewItem's Visible property has been set based on the deletion button click, // So at one place i have to get the count of rows which are visible and proceed // with related buttons enable/disable operation. }

    Read the article

  • wpf manually generate TreeViewItem container

    - by viky
    I am creating a TreeView at runtime. It has several nodes(TreeViewItem), each one having a name. Initially it is collapsed. A separate comboBox displays Names of all TreeViewItem. I have to highlight a TreeViewItem based on the Name selected. I am using a recursive function and gets the TreeViewItem container like this: if (parent.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) continue; TreeViewItem container = parent.ItemContainerGenerator.ContainerFromItem(child).As<TreeViewItem>(); but it is parent.ItemContainerGenerator.Status = GeneratorStatus.NotStarted for all the collapsed items. How can I generate containers for them manually(Without expanding them)?

    Read the article

  • Get a button in itemscontrol and add eventhandler to its click event

    - by rockdale
    I have a custom control shows a customer info with an itemscontrol shows this customer's invoices. within the itemscontrol, I have button, in my code behind I want to wire the button's click event to my host window, but do now know how. //public event RoutedEventHandler ViewDetailClick; public static readonly RoutedEvent ButtonViewClickEvent = EventManager.RegisterRoutedEvent( "ButtonViewClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(custitem)); public event RoutedEventHandler ButtonViewClick { add { AddHandler(ButtonViewClickEvent, value); } remove {RemoveHandler(ButtonViewClickEvent, value);} } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.lstInv = GetTemplateChild("lstInv") as ItemsControl; lstInv.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged); } private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { if (lstInv.ItemContainerGenerator.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { lstInv.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged; for (int i = 0; i < this.lstInv.Items.Count; i++) { ContentPresenter c = lstInv.ItemContainerGenerator.ContainerFromItem(lstInv.Items[i]) as ContentPresenter; DataTemplate dt = c.ContentTemplate; Grid grd = dt.LoadContent() as Grid; Button btnView = grd.FindName("btnView") as Button; if (btnView != null) { btnView.Click += new RoutedEventHandler(ButtonView_Click); //btnView.Click+= delegate(object senderObj, RoutedEventArgs eArg) //{ // if (this.ViewDetailClick != null) // { // this.ViewDetailClick(this, eArg); // } //}; } } private void ButtonView_Click(object sender, RoutedEventArgs e) { MessageBox.Show("clicked"); //e.RoutedEvent = ButtonViewClickEvent; //e.Source = sender; //RaiseEvent(e); } I succeed getting the btnView, then attach the click event, but the click event never get fired. Thanks in advance -rockdale

    Read the article

  • Do you like languages that let you put the "then" before the "if"?

    - by Matt Hamilton
    I was reading through some C# code of mine today and found this line: if (ProgenyList.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) return; Notice that you can tell without scrolling that it's an "if" statement that works with ItemContainerGenerator.Status, but you can't easily tell that if the "if" clause evaluates to "false" the method will return at that point. Realistically I should have moved the "return" statement to a line by itself, but it got me thinking about languages that allow the "then" part of the statement first. If C# permitted it, the line could look like this: return if (ProgenyList.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated); This might be a bit "argumentative", but I'm wondering what people think about this kind of construct. It might serve to make lines like the one above more readable, but it also might be disastrous. Imagine this code: return 3 if (x > y); Logically we can only return if x y, because there's no "else", but part of me looks at that and thinks, "are we still returning if x <= y? If so, what are we returning?" What do you think of the "then before the if" construct? Does it exist in your language of choice? Do you use it often? Would C# benefit from it?

    Read the article

  • WPF Accessing Items inside Listbox which has a UserControl as ItemTemplate

    - by Turker
    I have Window that has a ListBox ListBox(MyListBox) has a DataTable for its DataContext ListBox's ItemSource is : {Binding} Listbox has a UserControl(MyUserControl) as DataTemplate UserControl has RadioButtons and TextBoxes (At first They're filled with values from DataTable and then user can change them) Window has one Submit Button What I want to do is, when user clicks the submit button For each ListBox Item, get the values form UserControl's TextBoxes and RadioButtons. I was using that method for this job : foreach(var element in MyListBox.Items) { var border = MyListBox.ItemContainerGenerator.ContainerFromItem(element)as FrameworkElement; MyUserControl currentControl = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(myBorder,0) as Border,0)as ContentPresenter,0)as MyUserControl; //And use currentControl } I realised nothing when using 3-5 items in Listbox. But when I used much more items, I saw that "var border" gets "null" after some elements looped in foreach function. I found the reason here : http://stackoverflow.com/questions/1675926/listview-itemcontainergenerator-containerfromitemitem-return-null-after-20-item So what can I do now? I want to access all items and get their values sitting on user controls. Thanks

    Read the article

  • WPF - Overlapping Custom Tabs in a TabControl and ZIndex

    - by Rachel
    Problem I have a custom tab control using Chrome-shaped tabs that binds to a ViewModel. Because of the shape, the edges overlap a bit. I have a function that sets the tabItem's ZIndex on TabControl_SelectionChanged which works fine for selecting tabs, and dragging/dropping tabs, however when I Add or Close a tab via a Relay Command I am getting unusual results. Does anyone have any ideas? Default View http://i193.photobucket.com/albums/z197/Lady53461/tabs_default.jpg Removing Tabs http:/i193.photobucket.com/albums/z197/Lady53461/tabs_removing.jpg Adding 2 or more Tabs in a row http:/i193.photobucket.com/albums/z197/Lady53461/tabs_adding.jpg Code to set ZIndex private void PrimaryTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source is TabControl) { TabControl tabControl = sender as TabControl; ItemContainerGenerator icg = tabControl.ItemContainerGenerator; if (icg.Status == System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated) { foreach (object o in tabControl.Items) { UIElement tabItem = icg.ContainerFromItem(o) as UIElement; Panel.SetZIndex(tabItem, (o == tabControl.SelectedItem ? 100 : 90 - tabControl.Items.IndexOf(o))); } } } } By using breakpoints I can see that it is correctly setting the ZIndex to what I want it to, however the layout is not displaying the changes. I know some of the changes are in effect because if none of them were working then the tab edges would be reversed (the right tabs would be drawn on top of the left ones). Clicking a tab will correctly set the zindex of all tabs (including the one that should be drawn on top) and dragging/dropping them to rearrange them also renders correctly (which removes and reinserts the tab item). The only difference I can think of is I am using the MVVM design pattern and the buttons that Add/Close tabs are relay commands. Does anyone have any idea why this is happening and how I can fix it?? p.s. I did try setting a ZIndex in my ViewModel and binding to it, however the same thing happens when adding/removing tabs via the relay command. EDIT: Being a new user I couldn't post images and could only post 1 link. Images just show a picture of what the tags render as after each scenario. Adding more then 1 at a time will not reset the zindex of other recently-added tabs so they go behind the tab on the Right, and closing tabs does not correctly render the ZIndex of the SelectedTab that replaces it and it shows up behind the tab on its right.

    Read the article

  • WPF DataGrid programmatic multiple row selection

    - by MicMit
    Is there anything simpler than sample below ? I do have observable collection ( "list" in the code ) bound to DataGrid lstLinks for (int i = 0; i < list.Count ; i++) { object rowItem = lstLinks.Items[i] ; DataGridRow visualItem = (DataGridRow)lstLinks.ItemContainerGenerator.ContainerFromItem(rowItem); if (list[i].Changed) visualItem.IsSelected = false; else visualItem.IsSelected = false; }

    Read the article

  • Setting a DataGrid background color based on the previous row

    - by Zipper
    I'm trying to setup a grid where I do column sorting, but I wanted to do zebra striping, only rather than every other row or every x rows, I want it to be based on the value of cells. i.e. All cells that contain 0 have a blue background, the next value would have a white background, the next value would be blue, etc.... The problem I have is that I can't seem to find where to actually do the setting of the background colors. I'm using a custom sorter and I tried setting it in there after I re-order the list and set the data source, but it appears that when the data source is set, that the rows don't exist yet. I tried using the DataContextChanged, but that event doesn't seem to be firing. Here is what I have now. namespace Foo.Bar { public partial class FooBar { List<Bla> ResultList { get; set; } SolidColorBrush stripeOneColor = new SolidColorBrush(Colors.Gold); SolidColorBrush stripeTwoColor = new SolidColorBrush(Colors.White); //********************************************************************************************* public Consistency() { InitializeComponent(); } //********************************************************************************************* override protected void PopulateTabWithData() { ResultList = GetBlas(); SortAndGroup("Source"); } //********************************************************************************************* private void SortAndGroup(string colName) { IOrderedEnumerable <Bla> ordered = null; switch (colName) { case "Source": case "ID": ordered = ResultList.OrderBy(r => r.Source).ThenBy(r => r.ID); break; case "Name": ordered = ResultList.OrderBy(r => r.Source).ThenBy(r => r.Name); break; case "Message": ordered = ResultList.OrderBy(r => r.Message); break; default: throw new Exception(colName); } ResultList = ordered.ThenBy(r => r.Source).ThenBy(r => r.ID).ToList(); // tie-breakers consistencyDataGrid.ItemsSource = null; consistencyDataGrid.ItemsSource = ResultList; ColorRows(); } //********************************************************************************************* private void consistencyDataGrid_Sorting(object sender, System.Windows.Controls.DataGridSortingEventArgs e) { SortAndGroup(e.Column.Header.ToString()); e.Handled = true; } private void ColorRows() { for (var i = 0; i < ResultList.Count; i++) { var currentItem = ResultList[i]; var row = myDataGrid.ItemContainerGenerator.ContainerFromItem(currentItem) as DataGridRow; if (row == null) { continue; } if (i > 0) { var previousItem = ResultList[i - 1]; var previousRow = myDataGrid.ItemContainerGenerator.ContainerFromItem(previousItem) as DataGridRow; if (currentItem.Source == previousItem.Source) { row.Background = previousRow.Background; } else { if (previousRow.Background == stripeOneColor) { row.Background = stripeTwoColor; } else { row.Background = stripeOneColor; } } } else { row.Background = stripeOneColor; } } } } } }

    Read the article

  • WPF DataGrid - Can't Use Mouse To Scroll Because Of Drag Drop

    - by OrPaz
    Hello, I am using a datagrid that is allowing to drag its rows. My problem is that when i try to scroll down on my grid using the mouse on the side scroller, i get the 'no enterance' sign that means that "drag and drop is not allowed here, dude...". How can i modify my drag and drop function to recognize that this is not a drag and drop action, but a scroll mouse action? private new void MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { Point currentPosition = e.GetPosition(GridUC); Object selectedItem = GridUC.SelectedItem; if (selectedItem == null) return; DragDropContainerObject ddObject = new DragDropContainerObject(typeof(Actor), selectedItem); DataGridRow container = (DataGridRow)GridUC.ItemContainerGenerator.ContainerFromItem(selectedItem); if (container != null) { DragDropEffects finalDropEffect = DragDrop.DoDragDrop(container, ddObject, DragDropEffects.Link); } } }

    Read the article

  • How can I access the ListViewItems of a WPF ListView?

    - by David Schmitt
    Within an event, I'd like to put the focus on a specific TextBox within the ListViewItem's template. The XAML looks like this: <ListView x:Name="myList" ItemsSource="{Binding SomeList}"> <ListView.View> <GridView> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <!-- Focus this! --> <TextBox x:Name="myBox"/> I've tried the following in the code behind: (myList.FindName("myBox") as TextBox).Focus(); but I seem to have misunderstood the FindName() docs, because it returns null. Also the ListView.Items doesn't help, because that (of course) contains my bound business objects and no ListViewItems. Neither does myList.ItemContainerGenerator.ContainerFromItem(item), which also returns null.

    Read the article

  • WPF ItemsControl - how to know when the items finished loading, so that I can focus the first one?

    - by Tomáš Kafka
    Hi everyone, I have an ItemsControl in my View, that is bound to an ObservableCollection from ViewModel. The collection is filled, and afterwards an event from VM to view is raised (think search results and SearchFinished event). I would like to move keyboard focus to the first item in an ItemsControl, but when I do it in View's code-behind when handling SearchFinished, the items are not yet rendered (the collection is filled already, but wpf's rendering is asynchronous and didn't happen yet), so there is nothing to focus (Focus() needs to have the items' visual tree already constructed). I wanted to do (myItemsControl.ItemContainerGenerator.ContainerFromIndex(0) as UIElement).Focus();, but as the 0th item is not yet loaded, ContainerFromIndex(0) returns null. I tried delaying it with Dispatcher.BeginInvoke... with low priority, but that is dependent on exact timing and usually doesn't work. How can I wait until the first item in ItemsControl is Loaded?

    Read the article

  • Access to DataTemplate Control of WPF Toolkit DataGridCell at Runtime, How?

    - by LukePet
    I have a DataGrid defined with WPF Toolkit. The CellEditingTemplate of this DataGrid is associated at runtime with a custom function that build a FrameworkElementFactory element. Now I have to access to control that is inserted inside DataTemplate of CellEditingTempleta, but I do not know how to do. On web I found a useful ListView Helper... public static class ListViewHelper { public static FrameworkElement GetElementFromCellTemplate(ListView listView, Int32 column, Int32 row, String name) { if (row >= listView.Items.Count || row < 0) { throw new ArgumentOutOfRangeException("row"); } GridView gridView = listView.View as GridView; if (gridView == null) { return null; } if (column >= gridView.Columns.Count || column < 0) { throw new ArgumentOutOfRangeException("column"); } ListViewItem item = listView.ItemContainerGenerator.ContainerFromItem(listView.Items[row]) as ListViewItem; if (item != null) { GridViewRowPresenter rowPresenter = GetFrameworkElementByName<GridViewRowPresenter>(item); if (rowPresenter != null) { ContentPresenter templatedParent = VisualTreeHelper.GetChild(rowPresenter, column) as ContentPresenter; DataTemplate dataTemplate = gridView.Columns[column].CellTemplate; if (dataTemplate != null && templatedParent != null) { return dataTemplate.FindName(name, templatedParent) as FrameworkElement; } } } return null; } private static T GetFrameworkElementByName<T>(FrameworkElement referenceElement) where T : FrameworkElement { FrameworkElement child = null; for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceElement); i++) { child = VisualTreeHelper.GetChild(referenceElement, i) as FrameworkElement; System.Diagnostics.Debug.WriteLine(child); if (child != null && child.GetType() == typeof(T)) { break; } else if (child != null) { child = GetFrameworkElementByName<T>(child); if (child != null && child.GetType() == typeof(T)) { break; } } } return child as T; } } this code work with the ListView object but not with the DataGrid object. How can use something like this in DataGrid?

    Read the article

  • WPF: ListView inside LIstViewItem: How to support button_click

    - by Bartek
    Hi I have problem with using buttons that are placed in the itemtemplate of the listview which is placed in the itemtemplate of the outer listview. I'll try to simplify the code to show only the idea. I have a objects collection which looks like this: Main object contains a list of innerObjects. Every innerObject contains a list of objects that contain some strings. mainObject listItem innerListItem string string innerListItem string string listItem innerListItem string string I set a mainObject as a itemsSource to the ListView. This listView has a ItemTemplate. This ItemTemplate contains some buttons and inner ListView. Inner ListView also has the item template that contains a button (deleteButton). Pressing this deleteButton I want to delete items (innerListItem) for which this button was created. I can use such functionality when I have a sigle listView. private void clearAndList_Click(object sender, RoutedEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is System.Windows.Controls.ListViewItem)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) { return; } ANDconditionsList andList = (ANDconditionsList)ConditionsList.ItemContainerGenerator.ItemFromContainer(dep); orConditionsList.RemoveConditionsSet(andList); } I can't use the same functionality because I can only use the name of the ConditionsList which is the mail listview. The idea is to find the innerlistview and use it instead of ConditionsList, however I don't know if it will work. If anyone have some samples concerning using listview in listview or how to operate the button in a different way please help me

    Read the article

  • How to determine if an item is the last one in a WPF ItemTemplate?

    - by Mike
    Hi everyone, I have some XAML <ItemsControl Name="mItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Mode=OneWay}" KeyUp="TextBox_KeyUp"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> that's bound to a simple ObservableCollection private ObservableCollection<string> mCollection = new ObservableCollection<string>(); public MainWindow() { InitializeComponent(); this.mCollection.Add("Test1"); this.mCollection.Add("Test2"); this.mItemsControl.ItemsSource = this.mCollection; } Upon hitting the enter key in the last TextBox, I want another TextBox to appear. I have code that does it, but there's a gap: private void TextBox_KeyUp(object sender, KeyEventArgs e) { if (e.Key != Key.Enter) { return; } TextBox textbox = (TextBox)sender; if (IsTextBoxTheLastOneInTheTemplate(textbox)) { this.mCollection.Add("A new textbox appears!"); } } The function IsTextBoxTheLastOneInTheTemplate() is something that I need, but can't figure out how to write. How would I go about writing it? I've considered using ItemsControl.ItemContainerGenerator, but can't put all the pieces together. Thanks! -Mike

    Read the article

  • Retrieve a TextBox element dinamically created and Focus it

    - by user335444
    Hi, I have a collection (VariableValueCollection) of custom type VariableValueViewModel objects binded with a ListView. WPF Follow: <ListView ItemsSource="{Binding VariableValueCollection}" Name="itemList"> <ListView.Resources> <DataTemplate DataType="{x:Type vm:VariableValueViewModel}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="180"></ColumnDefinition> </Grid.ColumnDefinitions> <TextBox TabIndex="{Binding Path=Index, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Grid.Column="0" Name="tbValue" Focusable="True" LostFocus="tbValue_LostFocus" GotFocus="tbValue_GotFocus" KeyDown="tbValue_KeyDown"> <TextBox.Text> <Binding Path="Value" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay"> <Binding.ValidationRules> <ExceptionValidationRule></ExceptionValidationRule> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> </Grid> </DataTemplate> </ListView.Resources> </ListView> My Goal is to add a new row when I press "enter" on last row, and Focus the new row. To do that, I check that row is the last row and add a new row in that case. But I don't know how to focus the new TextBox... Here the KeyPressed method: private void tbValue_KeyDown(object sender, KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Enter) { DependencyObject obj = itemList.ContainerFromElement((sender as TextBox)); int index = itemList.ItemContainerGenerator.IndexFromContainer(obj); if( index == (VariableValueCollection.Count - 1) ) { // Create a VariableValueViewModel object and add to collection. In binding, that create a new list item with a new TextBox ViewModel.AddNewRow(); // How to set cursor and focus last row created? } } } Thank's in advance...

    Read the article

  • how to find a control inside ItemsPanelTemplate in wpf?

    - by kakopappa
    I am trying to access a Grid inside the DataTemplate while the ItemsControl is binded by ItemsSource. this is the full XMAL code, How do i find a certain element from outside? for (int i = 0; i < allViewControl.Items.Count; i++) { var container = allViewControl.ItemContainerGenerator.ContainerFromItem(allViewControl.Items[i]) as FrameworkElement; var grid = allViewControl.ItemTemplate.FindName("grid", container) as DataGrid; } i found this always returning null ? <ScrollViewer Grid.Row="0" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto"> <ItemsControl x:Name="allViewControl" Focusable="False" HorizontalContentAlignment="Center" Grid.IsSharedSizeScope="true" ItemsSource="{Binding AllClassCharacters}" ItemTemplate="{StaticResource CharacterViewModelTemplate}" > <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Extensions:AnimatedWrapPanel IsItemsHost="true" /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> </ScrollViewer> <DataTemplate x:Key="CharacterViewModelTemplate" DataType="{x:Type ViewModel:CharacterViewModel}"> <Grid x:Name="grid" Width="200" Height="Auto" MinHeight="115" Margin="1" MinWidth="130" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" RenderTransformOrigin="0.5,0.5" Background="#66000000" > <Grid.RowDefinitions> <RowDefinition Height="70"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <ProgressBar x:Name="playerProgressBar" VerticalAlignment="Top" Background="Transparent" Height="5" Width="Auto" Value="0" Visibility="Collapsed" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan ="2" Grid.RowSpan="2" Foreground="White" BorderThickness="0" Style="{DynamicResource ProgressBarStyle1}" /> </Grid>

    Read the article

  • navigate all items in a wpf tree view

    - by Brian Leahy
    I want to be able to traverse the visual ui tree looking for an element with an ID bound to the visual element's Tag property. I'm wondering how i do this. Controls don't have children to traverse. I started using LogicalTreeHelper.GetChildren, which seems to work as intended, up until i hit a TreeView control... then LogicalTreeHelper.GetChildren doesnt return any children. Note: the purpose is to find the visual UI element that corresponds to the data item. That is, given an ID of the item, Go find the UI element displaying it. Edit: I am apparently am not explaining this well enough. I am binding some data objects to a TreeView control and then wanting to select a specific item programaticly given that business object's ID. I dont see why it's so hard to travers the visual tree and find the element i want, as the data object's ID is in the Tag property of the appropriate visual element. I'm using Mole and I am able to find the UI element with the appropriate ID in it's Tag. I just cannot find the visual element in code. LogicalTreeHelper does not traverse any items in the tree. Neither does ItemContainerGenerator.ContainerFromItem retrieve anything for items in the tree view.

    Read the article

  • csharp get value datatemplate element

    - by To-me
    Hello, Here is my code <ListBox x:Name="myList" IsSynchronizedWithCurrentItem="True" SelectionChanged="editElement"> <ListBox.ItemTemplate> <DataTemplate x:Name="ElementItemTemplate"> <StackPanel Name="stackPanelElementItem" Orientation="Horizontal"> <Label Name="SelectedItemlabel" Content="{Binding}" /> <Button Name="buttonDelElement" Click="btnDelElement">Delete</Button> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> private void btnDelElement(object sender, RoutedEventArgs e) { ListBoxItem lbi2 = (ListBoxItem)(lstCursus.ItemContainerGenerator.ContainerFromItem(myList.Items.CurrentItem)); String selectedItem = lbi2.Content.ToString(); MessageBox.Show("Selected Item " + selectedItem + " ."); private void editCursus(object sender, RoutedEventArgs e) { MessageBox.Show("Selected Item " + selectedItem + " ."); /* some code to edit selected item using linq */ } My issue, SelectionChange doesn't work anymore and when I click on buttonDelElement, Selected Item doesn't change immediately. Please, any ideas?

    Read the article

  • WPF - Only want one expander open at a time in grouped Listbox

    - by Portsmouth
    I have a UserControl with a templated grouped listbox with expanders and only want one expander open at any time. I have browsed through the site but haven't found anything except binding the IsExpanded to IsSelected which isn't quite what I want. I am trying to put some code in the Expanded event that would loop through Expanders and close all the ones that aren't the expander passed in the Expanded event. I can't seem to figure out how to get at them. I've tried ListBox.Items.Groups but didn't see how to get at them and tried ListBox.ItemContainerGenerator.ContainerFromItem (or Index) but nothing came back. Thanks <ListBox Name="ListBox"> <ListBox.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <Border BorderBrush="CadetBlue" BorderThickness="1"> <Expander BorderThickness="0,0,0,1" Expanded="Expander_Expanded" Focusable="False" IsExpanded="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType= {x:Type ListBoxItem}}}" > <Expander.Header> <Grid> <StackPanel Height="30" Orientation="Horizontal"> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" MinWidth="200" Padding="3" VerticalAlignment="Center" /> <TextBlock Foreground="Navy" FontWeight="Bold" Text=" Setups: " VerticalAlignment="Center" HorizontalAlignment="Right"/> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=ItemCount}" VerticalAlignment="Center" HorizontalAlignment="Right" /> </StackPanel> </Grid> </Expander.Header> <Expander.Content> <Grid Background="white" > <ItemsPresenter /> </Grid> </Expander.Content> <Expander.Style > <Style TargetType="{x:Type Expander}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="WhiteSmoke" Offset="0.0" /> <GradientStop Color="Orange" Offset="1.0" /> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsMouseOver" Value="false" <Setter Property="Background"> <Setter.Value>

    Read the article

  • WPF - How do I get an object that is bound to a ListBoxItem back

    - by JonBlumfeld
    Hi there here is what I would like to do. I get a List of objects from a database and bind this list to a ListBox Control. The ListBoxItems consist of a textbox and a button. Here is what I came up with. Up to this point it works as intended. The object has a number of Properties like ID, Name. If I click on the button in the ListBoxItem the Item should be erased from the ListBox and also from the database... <ListBox x:Name="taglistBox"> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="HorizontalAlignment" Value="Stretch"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <ContentPresenter HorizontalAlignment="Stretch"/> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Tag" Value="{Binding TagSelf}"></Setter> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <Grid HorizontalAlignment="Stretch"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Button Grid.Column="0" Name="btTag" VerticalAlignment="Center" Click="btTag_Click" HorizontalAlignment="Left"> <Image Width="16" Height="16" Source="/WpfApplication1;component/Resources/104.png"/> </Button> <TextBlock Name="tbtagBoxTagItem" Margin="5" Grid.Column="1" Text="{Binding Name}" VerticalAlignment="Center" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> The Textblock.Text is bound to object.Name and the ListBoxItem.Tag to object.TagSelf (which is just a copy of the object itself). Now my questions If I click the button in the listboxItem how do I get the listboxitem and the object bound to it back. In order to delete the object from the database I have to retrieve it somehow. I tried something like ListBoxItem lbi1 = (ListBoxItem)(taglistBox.ItemContainerGenerator.ContainerFromItem(taglistBox.Items.CurrentItem)); ObjectInQuestion t = (ObjectInQuestion) lbi1.Tag; Is there a way to automatically update the contents of the ListBox if the Itemssource changes? Right now I'm achieving that by taglistBox.ItemsSource = null; taglistBox.ItemsSource = ObjectInQuestion; I'd appreciate any help you can give :D Thanks in advance

    Read the article

  • WPF - Only want one expander open at a time

    - by Portsmouth
    I have a UserControl with a templated grouped listbox with expanders and only want one expander open at any time. I have browsed through the site but haven't found anything except binding the IsExpanded to IsSelected which isn't quite what I want. I am trying to put some code in the Expanded event that would loop through Expanders and close all the ones that aren't the expander passed in the Expanded event. I can't seem to figure out how to get at them. I've tried ListBox.Items.Groups but didn't see how to get at them and tried ListBox.ItemContainerGenerator.ContainerFromItem (or Index) but nothing came back. Thanks <ListBox Name="ListBox"> <ListBox.GroupStyle > <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <Border BorderBrush="CadetBlue" BorderThickness="1"> <Expander BorderThickness="0,0,0,1" Expanded="Expander_Expanded" Focusable="False" IsExpanded="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType= {x:Type ListBoxItem}}}" > <Expander.Header> <Grid> <StackPanel Height="30" Orientation="Horizontal"> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" MinWidth="200" Padding="3" VerticalAlignment="Center" /> <TextBlock Foreground="Navy" FontWeight="Bold" Text=" Setups: " VerticalAlignment="Center" HorizontalAlignment="Right"/> <TextBlock Foreground="Navy" FontWeight="Bold" Text="{Binding Path=ItemCount}" VerticalAlignment="Center" HorizontalAlignment="Right" /> </StackPanel> </Grid> </Expander.Header> <Expander.Content> <Grid Background="white" > <ItemsPresenter /> </Grid> </Expander.Content> <Expander.Style > <Style TargetType="{x:Type Expander}"> <Style.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <GradientStop Color="WhiteSmoke" Offset="0.0" /> <GradientStop Color="Orange" Offset="1.0" /> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsMouseOver" Value="false" <Setter Property="Background"> <Setter.Value> </code>

    Read the article

  • WPF ContextMenu with bound items: Items.Count == 0 in ContextMenuOpening event

    - by OregonGhost
    I have a ContextMenu with the ItemsSource bound to the selected item of a list view, like this: <ContextMenu ItemsSource="{Binding Path=PlacementTarget.SelectedItem, RelativeSource={RelativeSource Self}, Converter={StaticResource possibleConverter}}"/> The possibleConverter enumerates all possible values for a property of the the selected item, which are shown in the context menu. In the Opened event of the context menu, I select the current value like this: var cm = e.OriginalSource as ContextMenu; if (cm != null) { var lv = cm.PlacementTarget as ListView; var field = lv.SelectedItem as Field; var item = cm.ItemContainerGenerator.ContainerFromItem(cm.Items.OfType<object>().Where(o => o.ToString().Equals(field.StringValue)).FirstOrDefault()) as MenuItem; if (item != null) { item.IsChecked = true; } } Not particularly elegant, but it works. With the debugger I verified that the ContextMenu.Items.Count property has a non-zero value when expected (i.e. cm.Items.Count is non-zero in the if). So far, so good. There are, however, items in the listview where the context menu will have no items. In this case, an empty menu is shown. I tried to suppress this in the ContextMenuOpening event in the list view, like this: var lv = sender as ListView; if (lv != null) { var cm = lv.ContextMenu; if ((cm != null) && (cm.Items.Count > 0)) { // Here we want to check the current item, which is currently done in the Opened event. } else { e.Handled = true; } } Seems like it should work. However, cm.Items.Count is always zero. This is true even if ListView.SelectedItem did not change: For an item with menu entries, the menu is shown correctly after the first click, so the data binding has already happend. It is shown correct the second time as well, but in any case, Items.Count is zero in the ContextMenuOpening event. What am I missing? How can I suppress empty context menus? Why is the count zero in the ContextMenuOpening handler, which is in Windows Forms (ContextMenuStrip.Opening) the canonical point where to do these things? EDIT: Upon further investigating, it turns out that in the ContextMenuOpening handler, any binding to the listview fails, which is why ItemsSource is null. I tried to bind via ElementName, via a FindAncestor relationship, all to no avail. The PlacementTarget is null during that event. An ugly hack worked though: In the ContextMenuOpening event, I assign the list view to the ContextMenu.Tag property, while the ItemsSource binding now binds to Tag.SelectedItem. This updates the binding, so Items.Count is what it should be. It's still strange. How can you do meaningful things in ContextMenuOpening other than replacing the menu or something, if the binding fails because somehow the context menu is out of context during the event? Was it only tested with static pre-defined menu items?

    Read the article

1