Get Listboxitem from listbox - c#

Hi this should be faily simple, however I don't know what I am doing wrong. I've been looking all over the internet seeing people make this work, even followed the tutorial on MSDN still nothing has worked for me.
I want to Iterate over a ListBox, and get the ListBoxItems so I can find the DataTemplate that I have added to it.
This is my code behind.
private void SetListBoxDataTemplate(ListBox MyListBox)
{
try
{
foreach (CustomDataTemplateObject dataobject in MyListBox.Items)
{
ListBoxItem lbi = (ListBoxItem)(MyListBox.ItemContainerGenerator.ContainerFromItem(dataobject));
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(lbi);
DataTemplate dt = myContentPresenter.ContentTemplate;
TextBlock tb = (TextBlock)dt.FindName("ListBoxItemTextBlock1", myContentPresenter);
ComboBox cb = (ComboBox)dt.FindName("ListBoxItemComboBox1", myContentPresenter);
tb.Text = dataobject.Text;
cb.ItemsSource = dataobject.ListColors;
}
}
catch (Exception ex)
{
MessageBox.Show(""+ex);
}
}
XAML looks like this:
<DataTemplate x:Key="ListBoxItemDataTemplate1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Black" BorderThickness="1 1 0 1" MinWidth="50">
<TextBlock Name="ListBoxItemTextBlock1" Background="{Binding ElementName=ListBoxItemComboBox1, Path=SelectedValue}" >
</TextBlock>
</Border>
<ComboBox Name="ListBoxItemComboBox1" />
</StackPanel>
</DataTemplate>*
<StackPanel>
<ListBox Name="ListBoxTest1" ItemTemplate="{DynamicResource ListBoxItemDataTemplate1}" />
</StackPanel>
I have tried with setting my itemtemplate to static to see if it works, and the method i'm calling from code behind, is called after I have populated my ListBoxs
My dataobject is NOT null, however when i call the line in my code behind, my lbi, ends up being null.
Any suggestions? thanks in advance!
FIRST UPDATE
This problem only occurs if i call the method in my constructor, so perhaps it's because it hasn't initialized the full group element section yet. However I want to do this as soon as possible. Am I perhaps forced to do it in a WindowLoaded event?
SECOND UPDATE
Code updated, Rachel's answer worked for iterating over my ListBoxItems, however the Listbox Has not fully rendered since i'm unable to reach the Datatemplate at this time. So MyListBox_GeneratorStatusChanged is not working for this problem, but it does get the ListBoxItems.

WPF's main thread runs items at different priority levels. Code that runs in the Constructor all gets run at Normal priority, while things like rendering the ListBox and it's items run at the Render priority level, which occurs after all Normal priority operations have finished.
This means that your entire Constructor gets run (including SetListBoxDataTemplate()) before your ListBox is even rendered and the items get generated.
If you want to run some code after the items are generated, use the ItemsContainerGenerator.StatusChanged event
// Constructor
MyListBox.ItemContainerGenerator.StatusChanged += MyListBox_GeneratorStatusChanged;
...
void MyListBox_GeneratorStatusChanged(object sender, EventArgs e)
{
// return if containers have not been generated yet
if (MyListBox.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
return;
// remove event
MyListBox.ItemContainerGenerator.StatusChanged -= MyListBox_GeneratorStatusChanged;
// your items are now generated
SetListBoxDataTemplate(MyListBox);
}
What are you trying to accomplish with this method anyways? It is a bit unusual for WPF, and there may be a much better WPF way of accomplishing your task.
Updated based on new code added to Question
A much better method of setting your Text and ItemsSource properties is to make use of WPF's data bindings.
Your DataTemplate should look like this:
<DataTemplate x:Key="ListBoxItemDataTemplate1">
<StackPanel Orientation="Horizontal">
<Border BorderBrush="Black" BorderThickness="1 1 0 1" MinWidth="50">
<TextBlock Text="{Binding Text}" Background="{Binding ElementName=ListBoxItemComboBox1, Path=SelectedValue}" >
</TextBlock>
</Border>
<ComboBox ItemsSource="{Binding ListColors}" />
</StackPanel>
</DataTemplate>*
A DataTemplate is like a cookie cutter. It's used to make the UI objects, but is not part of the UI object itself. All it does is tell WPF that "When you go to render this object, render it using this XAML". So the way your XAML gets rendered is
<ListBoxItem>
<StackPanel>
<Border>
<TextBlock Text="{Binding Text}" />
</Border>
<ComboBox ItemsSource="{Binding ListColors}">
</StackPanel>
</ListBoxItem>
In addition, the DataContext behind your ListBoxItem is the item from the collection bound to ListBox.ItemsSource, which based on your code should be CustomDataTemplateObject. That allows the bindings from the DataTemplate to work
If you're new to WPF and struggling to understand how exact the DataContext works, I'd recommend reading this article of mine: What is this "DataContext" you speak of?.
To summarize, WPF has two layers to an application: the UI layer and the Data Layer (DataContext). When you perform a basic binding like above, you are pulling data from the data layer into the UI layer.
So your ListBoxItem has a data layer of CustomDataTemplateObject, and the TextBlock.Text and ComboBox.ItemsSource bindings are pulling data from the data layer for use in the UI layer.
I'd also highly recommend using a utility like Snoop which lets you view the entire Visual Tree of a running WPF application to see how items get rendered. Its very useful for debugging or learning more about how WPF works.

You're confusing two jobs and mixing them into one. First, get access to the ListBoxItem:
private void SetListBoxDataTemplate(ListBox MyListBox)
{
foreach (ListBoxItem listBoxItem in MyListBox.Items)
{
}
}
Now you can get the DataTemplate from the ListBoxItem:
foreach (ListBoxItem listBoxItem in MyListBox.Items)
{
ContentPresenter presenter = FindVisualChild<ContentPresenter>(listBoxItem);
DataTemplate dataTemplate = presenter.ContentTemplate;
if (dataTemplate != null)
{
// Do something with dataTemplate here
}
}
The FindVisualChild method can be found in the How to: Find DataTemplate-Generated Elements page on MSDN.
UPDATE >>>
To answer your edit, yes, the constructor will be too early to try to access these DataTemplates because the Framework won't have applied them to all of the objects by then. It is best to use the FrameworkElement.Loaded Event to do these kinds of things, as that is the first event that can be called after the controls have all been initialised.

Related

C# WPF reach an object in ObservableCollection by binding a TreeViewItem

Im working on a WPF project trying to get information from an ImpactElement-object. That object is inside a ObservableCollection called ElementList. This ElementList is located inside another ObservableCollection called ListOfCreatedStacks that holds objects of the Class Stack.
It only shows the toString from the element (ImpactElement) inside ElementList. I want the ImpactElements variable ElementMark to be shown from each elemnt in ElementList.
This is how it looks right now One element added in the ElementList
I can create any numbers of Stack and inside each stack there´s a ElementList with different numbers of ImpactElement. Two stacks with different amount of ImpactElements in the ElementList
From these pictures you can see that each ImpactElement from the ElementList is shown as "IMPACT_Visual_Stacker.Model.ImpactElement" but i want it to be the variable ElementMark that is inside ImpactElement Class.
Here´s the code from different Classes.
public class Controller
{
public ObservableCollection<Stack> ListOfCreatedStacks { get { return listOfCreatedStacks; } set { listOfCreatedStacks = value; } }
}
public class Stack
{
public ObservableCollection<ImpactElement> ElementList { get { return elementList; } set { elementList = value; } }
public string Id { get { return id; } set { id = value; } }
}
public class ImpactElement
{
private string elementMark;
private int id;
private Vector3 sizeLWH;
private Vector3 positionXYZ;
private Vector3 rotationXYZ;
private Mesh elementMesh;
}
Here´s the XAML part.
<ListView ItemsSource="{Binding ListOfCreatedStacks}" HorizontalAlignment="Left" Margin="350, 200,0,0" Width="300">
<ListView.ItemTemplate>
<DataTemplate>
<TreeViewItem
Header="{Binding Id}"
IsExpanded="True">
<TreeViewItem
ItemsSource="{Binding ElementList}" Header="{Binding ElementMark}" IsExpanded="True">
</TreeViewItem>
</TreeViewItem>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I've tried a solution from the other StackOverflow i got from Ed.
The result ends up with only adding a Hiearchy object insted of my "ImpactElement"-objects.
This is what the tested XAML looks like :
<ListView ItemsSource="{Binding ListOfCreatedStacks}" HorizontalAlignment="Left" Margin="350, 200,0,0" Width="300">
<ListView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type System:String}"
ItemsSource="{Binding ListOfCreatedStacks}">
<TreeViewItem
Header="{Binding Id}"
IsExpanded="True">
<HierarchicalDataTemplate DataType="{x:Type System:String}"
ItemsSource="{Binding ElementList}">
<TreeViewItem
Header="{Binding ElementMark}"
IsExpanded="True">
</TreeViewItem>
</HierarchicalDataTemplate>
</TreeViewItem>
</HierarchicalDataTemplate>
</ListView.ItemTemplate>
</ListView>
Feels like a miss some easy part that i dont understand. Thanks for the help.
First, Controller, ElementList, and ImpactElement should probably be implementing INotifyPropertyChanged. You can find a million examples of that on Stack Overflow and elsewhere. It's simple, and you can get help here if you run into any snags.
What that will do is cause the UI to update if you change any bound property values on those objects while they're visible in the UI. The ObservableCollections will notify the UI if you add or remove items, but they can't notify the UI if some property of one of items happens to change.
Second, ImpactElement has only private fields. Since the private fields were omitted on the other classes, I'm guessing this was just an oversight when you copied the code. But you can only bind to public properties. Must be public, must be a property with a get and usually a set.
I'm hoping that you've assigned an instance of Controller to your DataContext. If you didn't, the tree won't populate.
I found WPF's TreeView baffling at first, and I wasn't new to XAML when I first looked at it. Do a bunch of simple examples (and come here for help if you need it), don't just paste in the XAML I gave you. It'll snap into focus.
Finally, you did a lot of things in your XAML that weren't done in the example. I don't know why you did those things, but you can't just go doing stuff at random. It doesn't work well. But as I said the learning curve on this one is tough, so no harm done.
So here's the XAML:
<TreeView
ItemsSource="{Binding ListOfCreatedStacks}"
HorizontalAlignment="Left"
Margin="350, 200,0,0"
Width="300">
<TreeView.ItemContainerStyle>
<Style
TargetType="TreeViewItem"
BasedOn="{StaticResource {x:Type TreeViewItem}}"
>
<Setter Property="IsExpanded" Value="True" />
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate
DataType="{x:Type local:Stack}"
ItemsSource="{Binding ElementList}"
>
<Label Content="{Binding Id}" />
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate
DataType="{x:Type local:ImpactElement}"
>
<Label Content="{Binding ElementMark}" />
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
So the TreeView's ItemsSource is ListOfCreatedStacks.
We give the TreeView an ItemContainerStyle which will apply to every TreeViewItem in the tree. We only do that so we can set IsExpanded. There's no other way to get to the TreeViewItems. We could also give the top-level item template an ItemContainerStyle of its own, which would only affect its children, if we wanted to do something different with those. But we don't need to.
And we give the TreeView an ItemTemplate. That is how we show a TreeViewItem how to display one of the TreeView's children. When you look at the HierarchicalDataTemplate, it's a bit like a TreeView: It's got an ItemsSource, which we bind to a property of Stack which contains the children of the Stack. It has an ItemTemplate for its own children. It could, as I said, have an ItemContainerStyle, but we'll just let it inherit the one we set on the TreeView.
It's recursive: A tree node is very much like a whole tree.
If you don't give a HierarchicalDataTemplate an ItemTemplate of its own, the TreeViewItems it applies to will just use that one as the template for their own children, and the children will do the same. If you gave ImpactElement a child collection of ImpactElements, the tree could be two dozen levels deep without making a single change in the XAML above.
Any DataTemplate or HierarchicalDataTempate can have a DataType property. That is the type of viewmodel item being displayed by the template. I don't know where you got System:String from.
In this particular case1, DataType serves no purpose but to help you keep things straight when you're editing the XAML: It reminds you which template at which level of recursion applies to which collection item, and he's Intellisense help you out as well.
Finally, we have the content of the HierarchicalDataTempate:
<Label Content="{Binding Id}" />
That could be any single XAML element, but it could be a Grid or a StackPanel containing a whole UI if you wanted. You can put anything in there. You could put a whole different TreeView in there.
Lastly, you should learn to do layout with StackPanel and Grid columns and rows. This margin business is a nightmare if you want to rearrange anything. I presume you're using the Design mode in VS? All I use that for is to preview what I've done by hand in the XAML. Properly done, in XAML layout everything's positioned relative to its parent and siblings. Maybe it has a fixed width and/or height, usually a small margin -- single digits -- just to create space between neighbors, not for absolute positioning. Once you get used to it, it's a really nice way to work with stuff. A lot like HTML.
1 For the other uses of the DataType property of a DataTemplate or HierarchicalDataTemplate, see "implicit datatemplates", and here's a more complicated example for doing it with treeview items. If you're already struggling to digest all this, don't go look at that stuff, just focus on the case I gave you above. That's more than enough. Data templates are a learning curve, and adding recursion just makes everything weirder.

In my C# XAML Windows 8.1 app, how can I iterate over my ListView?

I'm new to Windows 8.1 development, XAML, and C#, so if this question is rudimentary, please forgive me.
I've got a <Page> in my app that contains a <ListView>, like so:
<ListView ItemsSource="{Binding Mode=TwoWay}" x:Name="ListView_Statistical">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Style="{StaticResource SubheaderTextBlockStyle}" Width="100" Margin="10,20">
<Run Text="X/Y " />
<!--<Run Text="{Binding Source={StaticResource ThisPage}, Path=i}" />-->
</TextBlock>
<TextBox HorizontalAlignment="Left" Text="{Binding xVal}" PlaceholderText="X" InputScope="Number" FontSize="28" Width="100" Margin="0,10,10,10" />
<TextBox HorizontalAlignment="Left" Text="{Binding yVal}" PlaceholderText="Y" InputScope="Number" FontSize="28" Width="100" Margin="0,10,10,10" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
In the Code Behind, I set up its DataContext like so:
ListView_Statistical.DataContext = this.statisticalPoints;
this.statisticalPoints is defined as such:
public ObservableCollection<StatisticalPoint> statisticalPoints
{
get { return (ObservableCollection<StatisticalPoint>)GetValue(statisticalPointsProperty); }
set {
SetValue(statisticalPointsProperty, value);
NotifyPropertyChanged("statisticalPoints");
}
}
// Using a DependencyProperty as the backing store for statisticalPoints. This enables animation, styling, binding, etc...
public static readonly DependencyProperty statisticalPointsProperty =
DependencyProperty.Register("statisticalPoints", typeof(ObservableCollection<StatisticalPoint>), typeof(EnterCalc), new PropertyMetadata(0));
I'm not sure if making this a DependencyProperty is necessary, or if making it follow INotifyPropertyChanged is necessary, but they don't seem to hurt.
Anyway, so in my constructor, I add a bunch of stuff to my statisticalPoints:
this.statisticalPoints = new ObservableCollection<StatisticalPoint>();
this.statisticalPoints.Add(new StatisticalPoint() { xVal = 1.0, yVal = 2.0 });
this.statisticalPoints.Add(new StatisticalPoint() { xVal = 33.0, yVal = 44.0 });
this.statisticalPoints.Add(new StatisticalPoint() { xVal = 555.0, yVal = 666.0 });
this.statisticalPoints.Add(new StatisticalPoint() { xVal = 0.7, yVal = 0.8 });
And when I load up the page, I do indeed see five rows in my ListView, populated as defined in my initialization of this.statisticalPoints.
The part I'm having trouble with is this:
I change the first value in the first <TextBox> in the ListView, then hit my save button... but ListView.Items doesn't have my change reflected, and I can't figure out how to look at the <TextBox> itself.
What I really want to do is have this bunch of statistical points modifiable by my user and be able to save their changes. To do that, I feel like I need to read the value in the <TextBox>es, but I can't figure out how to do that.
Alternatively, if the 'right way' to do this is to keep the data in this.statisticalPoints up-to-date when changes are made in the <TextBox>es, then I thought that a TwoWay binding Mode would do it, but neither ListView.Items nor this.statisticalPoints is changed when I make changes in the <TextBox>.
I do not have event handlers set up in those <TextBox> elements, as you can see, but do I need them, or am I missing something obvious?
Thanks in advance for any help you can give me!
To solve your initial problem, make the binding for each text box Mode="TwoWay". For reasons beyond my comprehension, the mode is default OneWay on pretty much everything in Windows Store Apps.
Making the ItemsSource binding two way does next to nothing, as the UI isn't changing the collection itself (by changing, I mean completely replacing). To iterate over your collection, just iterate over this.statisticalPoints and it will have the current data.
Now, you have a ton of other misconceptions so to try and run through them:
You never showed your save button, but the bindings either update your source or they don't. A save button is usually used to persist changes from the view model to the model.
Speaking of view models, you don't appear to have one. You shouldn't be directly setting the data context of controls, and certainly shouldn't have so much in code-behind. Create a proper view model object for your page, and bind ItemsSource to a public property of that view model.
NotifyPropertyChanged on a collection usually is unnecessary unless you are replacing the collection in code.
Having it won't hurt though, except, the setter of the backing property of a DependencyProperty (DP) is never called by the framework, so putting it there is just weird
And you don't really need a DP at all. DPs are there so a parent control can bind data to your special user control. Until you are using user controls, and really understand how DPs work, you shouldn't need to use them.

Working with elements inside a control that is bound to a collection

I have an ObservableCollection<string> that is bound to an ItemsControl whose template is just a Button. The content of this button are 2 TextBlock. I'm trying to use the PreviewMouseRightButtonUp event of the button to toggle the visibility of one of the textblocks, but without being able to use xaml names for elements in the template I'm hitting a wall. Is there a way of getting to the button's content elements via sender in that preview event, or some other way of doing this? This is related to a previous question I had that didn't quite get a usable answer (probably due to my explanation, hence this simplified example). It seems to me that what should happen is I should make a control based off button that adds a property for this toggle, but that is basically what I thought I had in the previous question that wasn't working. I feel like a property and trigger is what most would say is the right way to go?
xaml:
<ItemsControl x:Name="iC" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button PreviewMouseRightButtonUp="Button_PreviewMouseRightButtonUp">
<DockPanel>
<TextBlock Text="normal" DockPanel.Dock="Top"/>
<TextBlock Text="{Binding}" DockPanel.Dock="Top" Visibility="Collapsed"/>
</DockPanel>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
code behind:
ObservableCollection<string> x = new ObservableCollection<string>();
public MainWindow()
{
x.Add("1");
x.Add("2");
InitializeComponent();
iC.ItemsSource = x;
}
If you name the hidden text block "secondTextBlock", then this should work:
private void Button_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
DockPanel dockPanel = (DockPanel)((Button)sender).Content;
TextBlock text = (TextBlock)LogicalTreeHelper.FindLogicalNode(dockPanel, "secondTextBlock");
if (text != null)
{
text.Visibility = Visibility.Visible;
}
}
Regarding your comment below: yes, multiple instances of "secondTextBlock" will be created. See the Snoop screenshot below. But these multiple instances are OK; they do not have any negative impact.

Binding to code behind from custom control

I have a GridView that has several buttons. One of them is defined by the following template:
<DataTemplate x:Name="SubjectItemTemplate">
<Canvas Width="340" Height="170" VerticalAlignment="Top">
<Controls:ThreeImageButton HorizontalAlignment="Center" VerticalAlignment="Top" Margin="0,0,0,0"
NormalStateImageSource="{Binding NormalImage}"
HoverStateImageSource="{Binding HoverImage}"
PressedStateImageSource="{Binding PressedImage}" Command="{Binding Path=NavigateToUnitsPage}"
CommandParameter="{Binding}" Canvas.Left="0" Canvas.Top="0">
</Controls:ThreeImageButton>
</Canvas>
</DataTemplate>
Now I have a custom control as you can see, called ThreeImageButton. The button works fine when I use it on its own. But when I have it in the DataTemplate it won't bind properties to the code behind.
Right now, I have
x:Name="MyThreeImageButton"
in the custom button definition. And I connect to the code-behind like this:
<TextBlock Text="{Binding ElementName=MyThreeImageButton, Path=NormalStateImageSource}"/>
(This is just a test to display the text, in the actual code I would assign an image source to another property that is referred to by an element).
Right now, nothing is displayed in the TextBlock. What is the correct binding syntax I'm supposed to use to reach my properties?
Thanks!
Edit: I am setting the variable in the InitializeComponent function and I am using SetValue on the DependencyProperty.
Edit: Let me add the following information to be more clear
Scenario I:
In DataTemplate for GridView:
<UserControl CustomParameter="Literal Text">
In UserControl:
<TextBlock Text="{Binding CustomParameter}">
in UserControl .cs: this.DataContext = this
works!
Scenario II:
In DataTemplate for GridView:
<UserControl CustomParameter="{Binding ValueFromDataItem">
In UserControl:
<TextBlock Text="{Binding CustomParameter}">
in UserControl .cs: this.DataContext = this
nope!
I see,
So setting up a two-way binding to a custom property in a user control can be tricky because a user control cannot bind to a CLR property. Not only that but setting the data context on a user control has an unexpected effect on the binding inside it.
You can solve these problems with a little slight of code. Basically back your CLR properties with dependency properties and set the data context on a child element instead of the root user control.
Take a look at this sample. Let's pretend you have the following MainPage. That MainPage will eventually use our custom user control. So let's set the stage.
Here's the code-behind:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new /* your view model */
{
Title = Guid.NewGuid().ToString(),
};
}
}
In the code above I am simulating a complex view model with a simple anonymous class. It would be silly for you to implement your own like this, but at the same time it is silly for me to build a simple sample with the complete scaffolding. I bring this up only so it does not confuse you - as it could look like I am suggesting this approach in prod.
Here's the XAML:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<local:MyUserControl Text="{Binding Title}" />
</Grid>
In the XAML above, there is absolutely nothing special. I already have reference to the user control in the local namespace and I simply declare it here.
Okay, now that we have a consumer of the control, it's worth pointing out that in testing developers can mistakenly think that their binding is working because they test with literal values. Literal values bind fine. It's binding from the underlying view model that hick-ups.
Let's say another thing, some developers tend to avoid dependency properties because the require a little more typing. People remember that [kbd]propdp[/kbd] is a handy Visual Studio snippet that stubs out a dependency property for you.
Take a look at this user control. It has two controls, a TextBox and a TextBlock which are there to demonstrate the OneWay and TwoWay functionality of this binding approach. We also implement INotifyPropertyChanged on the user control. For the most part, adding a view model in the case of a user control is overkill because the user control already acts like a view model. It's up to the developer, but it seems dumb to me.
Here's the code behind:
public sealed partial class MyUserControl : UserControl, INotifyPropertyChanged
{
public MyUserControl()
{
this.InitializeComponent();
}
// text property
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValueDp(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyUserControl), null);
// bindable
public event PropertyChangedEventHandler PropertyChanged;
void SetValueDp(DependencyProperty property, object value,
[System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
{
SetValue(property, value);
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
In the ode above, I have create a "Text" property and backed it with a dependency property. For a matter of reuse I have also implemented SetValueDp() which could be used again and again if I had more than a single property. Even though this demo has but one, I wanted to include this because the repetitive logic should certainly be abstracted out like this.
Here's the XAML:
<Grid Background="Black" DataContext="{Binding ElementName=userControl}">
<StackPanel>
<TextBox Text="{Binding Text, Mode=TwoWay}"
MinHeight="100" Padding="15" FontWeight="Light" FontSize="50" />
<TextBlock Text="{Binding Text}"
MinHeight="100" Padding="15" FontWeight="Light" FontSize="50" />
</StackPanel>
</Grid>
In the XAML above, I do nothing special insofar as binding. The syntax simply binds to the Text property using the Mode appropriate to the control. Just like you would do normally. However, what's worth noticing is that the DataContext is NOT set on the user control. Instead, it is set on the Grid. As a point of fact, any control in the tree other than the user control could be used like this. Just don't set the data context of the user control.
That is it by the way.
I have tested it to make sure it works. Demonstrating both one and two way binding is pretty handy here. I might even turn this into a blog in case other developers want to find it and don't discover this question. Thanks for your question!
Best of luck!
As the comments alluded to, your DataTemplate is placing the datacontext of the items to whatever object you are adding to your list. This is not the same as the surrounding user control's data context. If you want to reference that datacontext's commands, do the following in the DataTemplate's bindings:
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.NormalImage}
What this is saying is to go out and find the user control ancestor and use its datacontext and then look for the NormalImage property. If you run into problems, check your output window for binding errors. It is very helpful in finding binding problems.

Disabling a TreeView item bound to an ItemsSource defined in xaml

I have a TreeView that I am binding to an ItemsSource that creates a CheckBox for each item. Here is the xaml:
<TreeView x:Name="ReasonTreeView" Height="Auto" Background="Transparent"
BorderThickness="0" IsTabStop="False"
ItemsSource="{Binding Path=AnswerOptions}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type QSB:Answer}" ItemsSource="{Binding Path=AnswerOptions}">
<StackPanel Orientation="Horizontal">
<CheckBox Margin="0,5"
IsChecked="{Binding Path=IsSelected}"
IsEnabled="{Binding Path=Value,
Converter={StaticResource ReasonValueToEnabledConverter}}"
Visibility="{Binding Path=AnswerOptions,
Converter={StaticResource ParentNodeVisConverter}}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
In my application I then create multiple instances of these. Depending on the instance of the TreeView, certain CheckBoxes need to be disabled so the user can not select them, however I'm uncertain of how I can access the individual items in the HierarchicalDataTemplate in the code.
After looking around for a while the only thing I can think of is to build the whole TreeView in the code behind instead of the xaml, but I would rather not have to resort to that. Is there anything else that I can do?
To help clarify my point and for illustrative purposes, this is essentially what I want to be able to do (in pseudocode): ReasonTreeView.ItemsSource[5].IsEnabled = false;
Which would disable the CheckBox (and any other controls in that HierarchicalDataTemplateItem) at index 5 of the TreeView's ItemsSource
Let me know if more information is needed
I meant that binding on the checkbox's isenabled property Path=Value. That Value member has to be bool and implement INotifyPropertyChanged then you can control IsEnabled from your model. Dont forget to add Mode=Twoway to your binding
Instead of accessing the CheckBox through Control.ItemsSource property you should make the change in your underlying collection (that is itemssource of your control). After making the change notify the View (your Control) that data has been changed so update the control.
Implement INotifyPropertyChanged in your underlying class and after changing the Property (which is responsible for Enabled/Disabled) value Notify the View.
If you are not familiar with concepts of Data Binding and INotifyPropertyChanged, I would suggest you to read some basic tutorials about it. It is one of the major feature of WPF which makes life very easy for doing things like yours

Categories