How to bind local variable in WPF - wpf

I have silverlight usercontrol. This contains Service Entity object. see below
public partial class MainPage : UserControl
{
public ServiceRef.tPage CurrentPage { get; set; }
...
}
I need to bind CurrentPage.Title to TextBox
My xaml is here
<TextBox Text="{Binding Path=CurrentPage.Title, RelativeSource={RelativeSource self}}"></TextBox>
But it is not work.
How to do it?

In order for that to work, you'll have to implement INotifyPropertyChanged on your class and raise the PropertyChanged event for CurrentPage when it's set (this also means you won't be able to use auto properties; you'll have to use your own private instance backing variable and code the get { } and set { } yourself).
What's happening is the control is binding to the value before you've set CurrentPage. Because you aren't notifying anyone that the property has changed, it does not know to refresh the bound data. Implementing INotifyPropertyChanged will fix this.
Or you could just manually set the Text property yourself in the setter.

Change your markup to
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=CurrentPage.Title}" />
By assigning RelativeSource={RelativeSource self} your are telling the TextBlock to bind to itself and look for a property named CurrentPage on the TextBlock itself and not the parent Window.

set the UpdateSourceTrigger="PropertyChanged" in the XAML.

Related

Difference Source and Datacontext in wpf

DataContext and Source seem to be very similar to me.
What are the advantages and disadvantages?
When to use which one?
With Source:
<TextBlock Text="{Binding Name, Source={StaticResource Person}}" />
Or the solution with DataContext:
public partial class DataContextSample : Window
{
public string Name {get; set;}
public DataContextSample()
{
InitializeComponent();
this.DataContext = this;
}
}
<TextBlock Text="{Binding Name}" />
A binding with out a specified Source binds to the DataContext property of the element.
The DataContext is a special property which, if not set, is redirected to the element's parent's DataContext. This prevents duplicate xaml (always setting the Source in every binding) and makes all bindings relative so it is easier to change the UI without having to adjust all Sources in the bindings.

Event binding to ViewModel events in XAML

WPF newbie here. Suppose my ViewModel class has an event SomethingHappened defined as:
Public Event SomethingHappened(message As String)
and there is a local resource in my View define as:
<local:MsgWindow x:Key="MsgWindow" Visibility="Hidden" >
The ViewModel is assigned as the DataContext of the View. How do I change the Visibility of my MsgWindow to Visible upon SomethingHappended?
I would define a bool property in your view model, create BoolToVisibilityConverter (implementing IValueConverter), and bind Visibility property in XAML to your model's property with the converter. Instead of raising the event, set your property (ensure your property raises PropertyChanged from INotifyPropertyChanged OR is a dependency property).
In the resources, declare:
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
Then in your view-model declare:
public bool Visible { get; set; }
And then, bind your component to this property with the converter
<local:MsgWindow x:Key="MsgWindow" Visibility="{Binding Visible, Converter={StaticResource BooleanToVisibilityConverter}}" >

How to bind a property in itemtemplate to a proptery in itemsource?

Consider this container:
public class ItemInfo : DependencyObject
{
public string Name { get; set; }
public ObservableCollection<SomeDataItem> DataValues { get; set; }
...
Dependency object registration and event handling
...
}
public class MyItemSource : ObservableCollection<ItemInfo>
{
...
}
Now, I wish to display this data in a listview where the control that displays the item is custom. For that, I'd set the MyItemSource to listview's ItemSource and define a ItemTemplate. However, it seems that I have no access to ItemInfo in the ItemTemplate. This is my XAML:
<Grid>
<ListBox ItemsSource="{StaticResource MyStaticDataSource}"
Grid.IsSharedSizeScope="True">
<ListBox.ItemTemplate>
<DataTemplate>
<local:ItemInfoUserControl x:Name="itemInfoUserControl"
Name = "{Binding Name}" <--- this doesn't work
Data = "{Binding DataValues}" <--- this doesn't work
Width="300" Height="200"
Grid.Row="1">
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Instead of binding to ItemSource's ItemInfo, it binds to the ItemInfoUserControl properties, which is not what I wish it to do. Is there a way to bind properties in itemtemplate to a property in itemsource ? Or is there an alternative approach to what i'm ultimately trying to accomplish ?
Thanks!
Well, first of all you need to use proper binding syntax:
Name = "{Binding Name}"
and
Data = "{Binding DataValues}"
Instead of just "Name = "Binding Name"" and "Data = "Binding DataValues"". Note the addition of "{" and "}" around your binding expression.
This might be enough to solve your problem, as long as Name and DataValues are DependencyProperties in ItemInfoUserControl. If not, you'll need to implement them as DependencyProperties in order to be able to bind to them in XAML. See here for a good MSDN article on defining custom dependency properties.
Edit: Also, just noticed -- you're setting both x:Name and Name. From this article on MSDN:
If Name is available as a property on the class, Name and x:Name can be used interchangeably as attributes, but a parse exception will result if both are specified on the same element. If the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.
Remove x:Name="itemInfoUserControl" and see if that helps.

wpf binding from a FindAncestor to Dependency Property of custom control

I've got a custom WPF control with a DependencyProperty MyString
I'm using the control within an ItemsControl on my View and want to fish a value out from the ViewModel.
As the DataContext of the control becomes each Item in the ItemsSource of the ItemsControl I thought I'd just be able to use FindAncestor but it dosnt seem to work ... can anyone see where I'm going wrong please?
Heres the XAML on the View ...
<Grid>
<ItemsControl ItemsSource="{Binding MyItems}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Name="myStack">
<ImportExceptions:ControlStrip MyString="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.MyStringOnViewModel}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
and heres the code behind my custom control where I've set up my dependency property ...
public partial class ControlStrip
{
public ControlStrip()
{
InitializeComponent();
}
public string MyString
{
get
{
return GetValue(MyStringProperty).ToString();
}
set
{
SetValue(MyStringProperty, value);
}
}
public static readonly DependencyProperty MyStringProperty =
DependencyProperty.RegisterAttached("MyString", typeof (string), typeof (ControlStrip));
}
The DataContext of the control doesn't change - the DataContext for the ImportExceptions:ControlStrip will be (unless explicitly specified) the next DataContext available as its goes 'up' the visual tree...
I infer from your code that you have set the DataContext of the View to a ViewModel with properties 'MyItems' and 'MyStringOnViewModel' - you should be able to simply bind the MyString property directly to the ViewModel, like
<ImportExceptions:ControlStrip MyString="{Binding Path=MyStringOnViewModel}" />
Your code looks fine. Probably you have made an error in the DataContext reference. In all likeliness the DataContext of the the ItemsControl already is MyStringOnViewModel. So, omit the .MystringOnViewModel after the DataContext in the Path attribute. If not can you give some more code, ore post a simplification of it that mimicks how the DataCon,text(s) is/are set?

How to change a WPF control's visibility from ViewModel

I've an WPF application where tried to implement MVVM pattern and Prism 2. I have a Usercontrol which has subscribed to an event fired from another Usercontrol. I would like to toggle visibility of few child elements in the subscribing control. Events are fired properly, even I am successfully able to bind data to some elements. How do I bind Visibility or any style property for that matter with the ViewModel and change them dynamically.
You can have a boolean property in your ViewModel and bind that property to the Visibility property of your controls. Since you will be asigning a boolean value and the Visibility property is expecting a Visibility enumeration value, you will have to use the BooleanToVisibilityConverter converter to make the conversion,
<Style.Resources>
<BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />
</Style.Resources>
<Image Visibility="{Binding Path=ShowImage,
Converter={StaticResource booleanToVisibilityConverter}}"/>
Hope this helps.
Ezequiel Jadib
Although adding a Boolean property and using a value converter works, I would recommend adding a property of type Visibility to your ViewModel, e.g.
public Visibility ImageVisibility
{
get { return shouldShowImage ? Visibility.Visible : Visibility.Collapsed }
}
The advantage of this method is you don't need to write a converter for every property you want to express in a visual way (e.g. for a stock level that turns a label red when it drops below 10, you could have a converter you use once or just expose a StockLabelBrush property from your VM)
There's a simple solution for people who run into this issue.
In your view model, create a "Visibility" property like so:
public Visibility ShowModifyButtons
{
get { return (Visibility)GetValue(ShowModifyButtonsProperty); }
set { SetValue(ShowModifyButtonsProperty, value); }
}
public static readonly DependencyProperty ShowModifyButtonsProperty =
DependencyProperty.Register("ShowModifyButtons", typeof(Visibility), typeof(FileMatchViewModel),
new UIPropertyMetadata(Visibility.Collapsed));
In your XAML, bind to it like so:
<Button Focusable="False" Content="Save" Width="100" Margin="10" Visibility="{Binding ShowModifyButtons}"/>
Now, from your view model, you can set ShowModifyButtons to Visibility.Collapsed or Visibility.Visible as needed.

Resources