UserControl Property Binding not Working - silverlight

Given the following code why would "My Stupid Text" never be bound to the UserControls text box?
MainPage.xaml
<Grid x:Name="LayoutRoot">
<Local:Stupid StupidText="My Stupid Text" />
</Grid>
Stupid.xaml
<UserControl x:Class="SilverlightApplication5.Stupid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Text="{Binding StupidText}" />
</Grid>
</UserControl>
Stupid.xaml.cs
public partial class Stupid : UserControl
{
public string StupidText
{
get { return (string)GetValue(StupidTextProperty); }
set { SetValue(StupidTextProperty, value); }
}
// Using a DependencyProperty as the backing store for StupidText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StupidTextProperty =
DependencyProperty.Register("StupidText", typeof(string), typeof(Stupid), new PropertyMetadata(string.Empty));
public Stupid()
{
InitializeComponent();
}
}

Do the following in the constructor of your user control (after InitializeComponent) and your textblock should be aware of its datacontext:
this.DataContext = this;

Give your Stupid control a name:-
<Local:Stupid x:Name="MyStupid" StupidText="My Stupid Text" />
Then you can use element binding like this:-
<TextBlock Text="{Binding StupidText, ElementName=MyStupid}" />

Related

Combobox usercontrol SelectedItem data binding in WPF container

This is my combobox usercontrol:
<UserControl x:Class="Hexa.Screens.UsrColorPicker"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Hexa.Screens"
xmlns:sys="clr-namespace:System;assembly=mscorlib" Height="40" Width="200" Name="uccolorpicker"
mc:Ignorable="d">
<UserControl.Resources>
<ResourceDictionary>
<ObjectDataProvider MethodName="GetType" ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
<ObjectDataProvider.MethodParameters>
<sys:String>System.Windows.Media.Colors, PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}" MethodName="GetProperties" x:Key="colorPropertiesOdp"/>
</ResourceDictionary>
</UserControl.Resources>
<ComboBox Name="superCombo" ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" SelectedValuePath="Name" SelectedValue="{Binding ElementName=uccolorpicker, Path=SelectedColor}" Text="{Binding ElementName=uccolorpicker,Path=Text}" SelectedItem="{Binding ElementName=uccolorpicker, Path=SelectedItem}" SelectedIndex="{Binding ElementName=uccolorpicker, Path=SelectedIndex}" SelectionChanged="superCombo_SelectionChanged" HorizontalContentAlignment="Stretch" >
<ComboBox.ItemTemplate>
<DataTemplate >
<WrapPanel Orientation="Horizontal" Background="Transparent">
<TextBlock Width="20" Height="20" Margin="5" Background="{Binding Name}" />
<TextBlock Text="{Binding Name}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontStyle="Italic" FontWeight="Bold" FontFamily="Palatino Linotype" />
</WrapPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
This is the code behind:
namespace Hexa.Screens
{
/// <summary>
/// Interaction logic for UsrColorPicker.xaml
/// </summary>
public partial class UsrColorPicker : UserControl
{
public UsrColorPicker()
{
InitializeComponent();
}
public Brush SelectedColor
{
get { return (Brush)GetValue(SelectedColorProperty); }
set { SetValue(SelectedColorProperty, value); }
}
public int SelectedIndex
{
get { return (int)GetValue(SelectedIndexProperty); }
set { SetValue(SelectedIndexProperty, value); }
}
public int SelectedItem
{
get { return (int)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
public string Text
{
get { return (string)GetValue(SelectedTextProperty); }
set { SetValue(SelectedTextProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedColor. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedColorProperty =
DependencyProperty.Register("SelectedColor", typeof(Brush), typeof(UsrColorPicker), new UIPropertyMetadata(null));
public static readonly DependencyProperty SelectedIndexProperty =
DependencyProperty.Register("SelectedIndex", typeof(int), typeof(UsrColorPicker), new UIPropertyMetadata(null));
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(int), typeof(UsrColorPicker), new UIPropertyMetadata(null));
public static readonly DependencyProperty SelectedTextProperty =
DependencyProperty.Register("Text", typeof(int), typeof(UsrColorPicker), new UIPropertyMetadata(null));
public static readonly RoutedEvent SettingConfirmedEvent =
EventManager.RegisterRoutedEvent("SettingConfirmedEvent", RoutingStrategy.Bubble,
typeof(RoutedEventHandler), typeof(UsrColorPicker));
public event RoutedEventHandler SettingConfirmed
{
add { AddHandler(SettingConfirmedEvent, value); }
remove { RemoveHandler(SettingConfirmedEvent, value); }
}
private void superCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RaiseEvent(new RoutedEventArgs(UsrColorPicker.SettingConfirmedEvent));
}
}
}
I am trying to set its SelectedItem,SelectedIndex thru xaml binding in my container's XAML as under:-
<local:UsrColorPicker x:Name="cmbItem_Group_back_color" HorizontalAlignment="Center" Width="205" Height="22" SettingConfirmed="cmbItem_Group_back_color_SettingConfirmed" SelectedColor ="{Binding Path=CurrentRec.Primary_Tone,Mode=TwoWay}" Canvas.Left="97" Canvas.Top="92" />
The code behind is as under:-
form_load()
{
this.DataContext = DataContract_ButtonSettings;
}
But the selecteditem's text is not showing on the combobox as it should.
I found the solution.It was a careless mistake..
The bug was nowhere in the code posted..Actually,i was using the usercontrol's selectedcolor property to bind to the backcolor property of an element in the view.The viewmodel updates the SelectedColor property of the ColorCombobox.The viewmodel was being updated from many places in the code behind.And at one place,the viewmodel's SelectedColor property was being set with the HEX equivalent of the known Color of System.Windows.Media.Colors Known color,and when the view model wud try to bind to that Hex element to the ComboBox,it did not find any matching entry for that Hex value in the dropdown list,and hence,though the background color of the control was being effected,the combobox text showed blank.:-).
anyways,solved it...thanks for your time Ed. :-).

Create UserControl with 2 TextBlock in WPF

I want to create an UserControl with a TextBlock as header and another TextBlock as content
HeaderTextBlock.xaml
<UserControl x:Class="GetPageDataFacebookAPI.HeaderTextBlock"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:GetPageDataFacebookAPI"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Header" Opacity=".6" Margin="5" />
<TextBlock Text="Text" Margin="5" />
</StackPanel>
</UserControl>
But how can I use it and binding value to Header and Content TextBlock?
<local:HeaderTextBlock Header="..." and Text="..." />
You just create dependency properties to expose those elements in code behind. Then when you use the control in another view you can do just that.
Add a name to the two TextBlock's and then add dependency properties to change them in the code behind.
<StackPanel Orientation="Horizontal">
<TextBlock Text="Header"
Opacity=".6"
Margin="5"
Name="TextBlockHeader"/>
<TextBlock Text="Text"
Margin="5"
Name="TextBlockText"/>
</StackPanel>
Code Behind for control...
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register(nameof(Header), typeof(string), typeof(HeaderTextBlock), new PropertyMetadata("", (s, e) => (s as HeaderTextBlock).TextBlockHeader.Text = (string)e.NewValue));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(nameof(Text), typeof(string), typeof(HeaderTextBlock), new PropertyMetadata("", (s, e) => (s as HeaderTextBlock).TextBlockText.Text = (string)e.NewValue));
Then you can use it in another view or control like so... Works with binding also.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<local:HeaderTextBlock Header="{Binding Header}" Text="Hello WOrld"/>
</Grid>
Create two plain CLR properties, or
Create two DependencyProperty corresponding to Header and Text if you need Binding.
Tutorial
You need to creat custom control, and not use userControl:
https://msdn.microsoft.com/en-gb/library/cc295235.aspx

Silverlight: How to bind to parent view's DataContext?

I have a ParentView that contains a childView
<UserControl ... x:Name="MyParentView">
<Grid>
<sdk:TabControl Name="ContactTabControl">
<sdk:TabItem Header="Contact" Name="CustomerTabItem">
<Grid>
<Views:CustomerView/>
</Grid>
</sdk:TabItem>
</sdk:TabControl>
</Grid>
</UserControl>
Within my CustomerView I would like to bind the Firstname textbox to Parent's DataContext. I have tried this inside the CustomerView:
<TextBox Text={Binding ElementName=MyParentView, Path=DataContext.Firstname} />
I have the feeling that CustomerView won't be able to see its parent at all, hence the ElementName "MyParentView" would never be found.
What is your advice on this?
I've done a similar thing but I just bound it directly to Path considering that if I don't give it explicit data context, it will lookup the hierarchy and find one that matches.
So this should get you what you want:
<TextBox Text={Binding Path=FirstName} />
if you need to specify explicit datacontext you can always do:
<Grid>
<Views:CustomerView DataContext={"CustomContextHere"}/>
</Grid>
An alternative solution to Maverik's is :
1 Define a dependency property in your customer view :
public partial class CustomerView : UserControl
{
public CustomerView()
{
InitializeComponent();
}
public static DependencyProperty FirstNameProperty =
DependencyProperty.Register("FirstName", typeof(string), typeof(CustomerView), new PropertyMetadata(string.Empty, CustomerView.FirstNameChanged));
public string FirstName
{
get { return (string)GetValue(FirstNameProperty); }
set { SetValue(FirstNameProperty, value); }
}
private static void FirstNameChanged(object sender, DependencyPropertyChangedEventArgs e)
{ }
}
2 Modify the customer view's textbox to bind to this dependency property (note the element binding "this")
<UserControl x:Class="SLApp.CustomerView"
x:Name="this"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox Text="{Binding Path=FirstName, ElementName=this, Mode=TwoWay}"/>
</Grid> </UserControl>
3 Modify the parent view and bind it's DataContext to the new dependency property
<sdk:TabControl Name="ContactTabControl">
<sdk:TabItem Header="Contact" Name="CustomerTabItem">
<Grid>
<local:CustomerView FirstName="{Binding ElementName=ContactTabControl, Path=DataContext}"/>
</Grid>
</sdk:TabItem>
</sdk:TabControl>
4 Set the parent's DataContext
public partial class MyParentView : UserControl
{
public MyParentView()
{
InitializeComponent();
ContactTabControl.DataContext = "A name";
}
}
Voila' it works. Not the most elegant solution but it gets the job done for your scenario

Dependency propery Binding Problem

Main WINDOW
<Window x:Class="dep2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:dep2"
Title="Window1" Height="300" Width="381">
<Grid>
<local:UserControl1></local:UserControl1>
<Button Height="23" HorizontalAlignment="Right" Margin="0,0,77,36" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Button</Button>
</Grid>
</Window>
public partial class Window1 : Window
{
UserControl1 uc = new UserControl1();
public Window1()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
uc.InfoText = "SAMPLE";
}
}
My User CONTROL
<UserControl x:Class="dep2.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="32" Width="300">
<Grid Height="30">
<StackPanel Background="LightCyan">
<TextBox Height="21" Name="textBlock1" Width="120" Text="{Binding Text}" />
</StackPanel>
</Grid>
</UserControl>
public partial class UserControl1 : UserControl
{
public string InfoText
{
get
{
return (string)GetValue(InfoTextProperty);
}
set
{
SetValue(InfoTextProperty, value);
}
}
public static readonly DependencyProperty InfoTextProperty =
DependencyProperty.Register(
"InfoText",
typeof(string),
typeof(UserControl1),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(ChangeText)));
private static void ChangeText(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
(source as UserControl1).UpdateText(e.NewValue.ToString());
}
private void UpdateText(string NewText)
{
textBox1.Text = NewText;
}
public UserControl1()
{
InitializeComponent();
DataContext = this;
}
}
Am getting my value in user control dependency property, but i cant able to bind my value to the text box.am using like this to bind Text="{Binding Text}" is it right,or how to bind my value in user control
i have attached my sample project here,
http://cid-08ec3041618e8ee4.skydrive.live.com/self.aspx/.SharedFavorites/dep2.rar
Can any one look and tell whats wrong in that,
everythng working well, but i cant bind the value in text box,
when u click the button u can see the passed value to usercontrol in message box, but i cant bind that value in text box.
Why????
Your code handles the callback from the dependency property and sets the text box value directly. This is not the role of this callback.
And by setting the Text property, you have lost the binding. Local property setting has a higher priority than bindings. See this blog

Expose DependencyProperty

When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this?
<UserControl x:Class="WpfApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Background="LightCyan">
<TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</StackPanel>
</UserControl>
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication3
{
public partial class UserControl1 : UserControl
{
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
public string Text
{
get { return GetValue(TextProperty) as string; }
set { SetValue(TextProperty, value); }
}
public UserControl1() { InitializeComponent(); }
}
}
That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencing properties by the UserControl's name.
<UserControl x:Class="WpfApplication3.UserControl1" x:Name="UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Background="LightCyan">
<TextBox Margin="8" Text="{Binding Path=Text, ElementName=UserControl1}" />
</StackPanel>
</UserControl>
Sometimes we've found ourselves making too many things UserControl's though, and have often times scaled back our usage. I'd also follow the tradition of naming things like that textbox along the lines of PART_TextDisplay or something, so that in the future you could template it out yet keep the code-behind the same.
You can set DataContext to this in UserControl's constructor, then just bind by only path.
CS:
DataContext = this;
XAML:
<TextBox Margin="8" Text="{Binding Text} />

Resources