The acceptecd answer here explains how a double click event can be realized for a TabItem.
I understand the approach except of one thing: <Label Content={Binding}>
What exactly does {Binding} mean here for the labels content?
From Binding.Path
... period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}"
which means it will bind whole object that is currently available in DataContext which then will be converted for display using default or custom template
EDIT
In this case TabItem hosts ContentPresenter with ContentSource set to Header which changes DataContext to whatever is currently available in Header therefore DataContext for Label will be set to string as defined in Header
Related
I have some problems about datacontext binding.
My app has virtualization listbox.
Sometimes Button is not fired dataContextChanged.
So I found this.
<Grid DataContext={Binding ~~>
<Button DataContext={Binding}/>
</Grid>
<Grid DataContext={Binding ~~>
<Button/>
</Grid>
My Code is first one. but It's not fired DataContextChanged sometimes, So I changed code to second one.
snoop said first one is from inherit, and second one is from parentTemplate.
What is different first one and second one?
TL;DR:
SomeProperty={Binding} will bind the SomeProperty to the ENTIRE DataContext object from the parent. SomeProperty does not have to be the DataContext from the child. In this special case I don't think there is any difference, since the DataContext is inherited anyways. You are simply explicitly stating, what is already the default. Discussed here
More Info:
Here is an explanation from the official documentation for
<Button DataContext={Binding}/>
As long as the binding already has a data context (for example, the
inherited data context coming from a parent element), and whatever
item or collection being returned by that context is appropriate for
binding without requiring further path modification, a binding
declaration can have no clauses at all: {Binding}. This is often the
way a binding is specified for data styling, where the binding acts
upon a collection. For more information, see Using Entire Objects as a Binding Source.
and from here
<ListBox ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="true"/>
The above example uses the empty binding syntax: {Binding}. In this
case, the ListBox inherits the DataContext from a parent DockPanel
element (not shown in this example). When the path is not specified,
the default is to bind to the entire object. In other words, in this
example, the path has been left out because we are binding the
ItemsSource property to the entire object. (See the Binding to
collections section for an in-depth discussion.)
In general, the DataContext is inherited from parent elements. So in your 2nd example the button gets the DataContext from the Grid. Example
"ItemsControl" are special: Example
I don't know what ~~ is, is this meant to be a placeholder?
Some more information on Bindings and Markup Extensions:
Link1
Link2
Link3
I have a usercontrol, and there is a Datacontext set for it. This usercontrol contains also a Dependency-Property. Now, i want simply bind to this property.
I think the problem has something to do with the wrong datacontext.
The dependency-Property in my usercontrol (called TimePicker) looks like this:
public TimeSpan Time
{
get { return (TimeSpan)GetValue(TimeProperty); }
set
{
SetValue(TimeProperty, value);
OnPropertyChanged();
}
}
public static readonly DependencyProperty TimeProperty = DependencyProperty.Register("Time", typeof (TimeSpan), typeof (TimePicker));
I try to use it like this:
<upDownControlDevelopement:TimePicker Grid.Row="1" Time="{Binding Path=TimeValue}" />
When i do this i get the following binding error:
System.Windows.Data Error: 40 : BindingExpression path error: 'TimeValue' property not found on 'object' ''TimePicker' (Name='TimePickerControl')'. BindingExpression:Path=TimeValue; DataItem='TimePicker' (Name='TimePickerControl'); target element is 'TimePicker' (Name='TimePickerControl'); target property is 'Time' (type 'TimeSpan')
Any help would be highly appreciated
Greetings Michael
PS: you can download the code at here
Although this has now been solved there seems to be some, in my opinion, inappropriate use of the DataContext.
When developing a custom reusable control, you should not set DataContext at all. What the DataContext will be, that is for the user of the control to decide, not for the developer. Consider the following common pattern of code:
<Grid DataContext="{Binding Data}">
<TextBox Text="{Binding TextValue1}" />
<!-- Some more controls -->
</Grid>
Notice that here, you are using the Grid control. The developer of the control (in this case, the WPF team), didn't touch the DataContext at all - that is up to you. What does it mean for you as a control developer? Your DependencyProperty definition is fine, but you shouldn't touch the DataContext. How will you then bind something inside your control to the DependencyProperty value? A good way is using a template (namespaces omitted):
<MyTimePicker>
<MyTimePicker.Template>
<ControlTemplate TargetType="MyTimePicker">
<!-- Stuff in your control -->
<TextBlock Text="{TemplateBinding Time}" />
<TextBox Text="{Binding Time, RelativeSource={RelativeSource TemplatedParent}}" />
</ControlTemplate>
<MyTimePicker.Template>
</MyTimePicker>
Note that TemplateBinding is always one-way only, so if you need any editing at all, you need to use normal binding (as you can see on the TextBox in the example).
This only means that the TextBlock/Box inside your control will get its Time value from your custom control itself, ignoring any DataContext you might have set.
Then, when you use the control, you do it like this (added to my first example):
<Grid DataContext="{Binding Data}">
<TextBox Text="{Binding TextValue1}" />
<!-- Some more controls -->
<MyTimePicker Time="{Binding TimeValue}" />
</Grid>
What just happened here is that the MyTimePicker does not have DataContext set anywhere at all - it gets it from the parent control (the Grid). So the value goes like this: Data-->(binding)-->MyTimePicker.Time-->(template binding)-->TextBlock.Text.
And above all, avoid doing this in the constructor of your custom control:
public MyTimePicker()
{
InitializeComponent();
DataContext = this;
}
This will override any DataContext set in XAML, which will make binding a huge pain (because you'll have to always set Source manually). The previous example would not work, and this wouldn't work either:
<MyTimePicker DataContext="{Binding Data}" Time="{Binding TimeValue}" />
You would think this is OK, but the DataContext will be resolved in the InitializeComponent() call, so the value will be immediately overwritten. So the binding to TimeValue will look for it in the control instead (which will, of course, fail).
Just don't touch the DataContext when developing a control and you'll be fine.
You don't need to override the data context of user control. You can use RelativeSource to point your binding source property i.e. TimeValue to any other source you like. E.g. If you have the source property in your window's class. You could simply point your binding target to the source in window's data context as follows:
{Binding Path=DataContext.TimeValue, RelativeSource={ RelativeSource AncestorType={x:Type Window}}}
Your error states that 'TimeValue' property not found on 'object' 'TimePicker', which means that the WPF Framework is looking at the 'TimePicker' object to resolve the 'TimeValue' property value. You must have somehow set the DataContext of the Window or UserControl that contains the 'TimePicker' object to an instance of the 'TimePicker' object.
Instead, it should be set to an instance of the class that declares the 'TimeValue' property. If you're using a view model, then you should set it to an instance of that:
DataContext = new YourViewModel();
If the 'TimeValue' property is declared in the Window or UserControl then you can set the DataContext to itself (although generally not recommended):
DataContext = this;
Please note that when data binding to the 'Time' property from inside your TimePicker control, you should use a RelativeSource Binding:
<TextBlock Text="{Binding Time, RelativeSource={RelativeSource
AncestorType={x:Type YourLocalPrefix:TimePicker}}}" ... />
Normally we are not setting datacontext directly.If u want to set datacontext create an instance of your usercontrol and set datacontext individually to each one.
In .NET/WP/WPF, I am looking to create my first user control that will render content using a DataTemplate and am wondering how to do that. Do I need to use the Content presenter and pass it a reference to the template or what? Thanks for the help guys!
The basic strategy for including templated content in other fixed content (like the XAML of a UserControl) is to define a set of Content properties (as DependencyProperties) on the containing control and then add a ContentPresenter (with appropriate bindings) as the placeholder into which the content will be injected. In the framework you can see an example of this in HeaderedContentControl which has both a normal Content property set, but also a parallel set of Header properties that are used as a second piece of content.
The properties you can define on your control (differing by platform) are:
Content
ContentTemplate
ContentTemplateSelector
ContentStringFormat
with whatever your custom name is substituted for "Content" in each. In your case you probably only have the first two. Then in your UserControl layout (which is actually defining the Content itself of the UserControl) just place a ContentPresenter and set it up to use your custom properties with the control itself as the Binding Source (ElementName, RelativeSource, or setting the DataContext somewhere to the UserControl itself):
<ContentPresenter Content="{Binding ElementName=MyControl, Path=MyExtraContent}"
ContentTemplate="{Binding ElementName=MyControl, Path=MyExtraContentTemplate}" />
In most cases (but not here) ContentPresenter is used inside a ControlTemplate where you can use a nice shortcut that's built in to bind all the content properties for you:
<ContentPresenter ContentSource="MyExtraContent"/>
You can get the same effect with ContentControl but it's adding extra elements to your visual tree since it's basically just a ContentTemplate containing a ContentPresenter that passes all the properties through. It does allow you to add some visual differences, like Background or Padding, or add a whole custom template but in cases like this you can do exactly the same thing by just adding other controls around your ContentPresenter.
I have a WPF UserControl that's housed in an element host on a WindowsForms.
The WPF UserControl contains a ListBox that uses a DataTemplate that has a data bound to aTextBlock:
<UserControl.Resources>
<DataTemplate x:Key="NewsListBoxTemplate">
<TextBlock Name="tbTemplate" Padding="30,0" FontSize="28"
Text="{Binding Path=newsE}" Foreground="Blue"/>
</DataTemplate>
</UserControl.Resources>
The DataContext is based on a DataSet that gets its data from a sql server database.
I've researched and seen the various answers on SO and can identify the TextBlock at run time. But what I want to do is to change the Binding Path for that TextBlock to point to a different field of the DataSet when the user makes a choice on the Windows Form at runtime.
There are only two database fields available as choices.
From the point where I've identified the TextBlock name as tbTemplate, can anyone suggest code I can use to switch between the two Paths?
You can use BindingOperations
BindingOperations.SetBinding(tbTemplate, TextBlock.TextProperty, new Binding("MyProperty"));
Follow the link.. to get the control with its name from the DataTemplate and do the binding for that...
tbTemplate.SetBinding(TextBlock.TextProperty, new Binding("PropertyName"));
On my XAML page I have a text block with following binding:
<TextBlock Width="{Binding ActualWidth, ElementName=SessionList, Mode=OneWay}" ... />
This binds to a grid view:
<GridView x:Name="SessionList" ItemsSource="{Binding Sessions}"... />
Now when the page first loads and data is available, the text block will be visible and have the correct width. When the page loads and there is no data, the text box will not be visible because of the bound width.
But ... when I load up data in the background and after a while the data comes in (through MVVM) the list will be show, but the text block width will not change accordingly, and setting it as TwoWay has no effect.
Any ideas/tips?
ActualWidth is not a property that you can bind to within WinRT. Not sure if you are showing static text or bound text. If bound text and data is same as GridView has then it should go away if data is null. If static data, then use a ValueConverter to set the visibility of the TextBlock based on the data being null/empty
Binding issues like this are usually caused by properties that are not bindable, i.e. they are not dependency properties and/or do not implement INotifyPropertyChanged. Whatever. I use a Attached Dependency Property or, if that does not cover enough, a behavior. Now behavior are not included in WinRT, but that problem has already been addressed ;-)