Binding a Dynamic Application.Resource WPF - User Control - wpf

I have a custom class:
class CustomClass
{
public string Test { get; set; }
CustomClass()
{
this.Test = "";
}
}
I'm declaring this custom class on a Application.Resources like that:
<Application.Resources>
<local:CustomClass x:Key="myobj"/>
</Application.Resources>
This resource is the DataContext of a grid and the TextBox binds the Test property, like that:
<Grid DataContext="{DynamicResource myobj}">
<TextBox Text="{Binding Path=Test, Mode=TwoWay}"></TextBox>
</Grid>
Suddenly at run-time, I change the value of the resource
this.Resources["myobj"] = new CustomClass() { Test = "12456" };
I want the value referenced on TextBox be always the value of the object that is currently on "myobj" resource, and I want change automatically the value of the current object when the value of Text property of the TextBox is changed, because of this, I used the Mode=TwoWay, but it's not happening.
I used WPF Inspector and I saw when the resource value is changed, binds a new cleared object and not my created object
I'm new in WPF sorry my english and my unknowledge;
Regards,
EDIT 1
It works implementing the code posted by ethicallogics, thanks! But sorry if I wasn't clear before, when binds a new resource as below
this.Resources["myobj"] = new instance;
it works fine when it is called inside the same window that this resource was declared, unlike when I call this line inside a UserControl, it seems that the UserControl doesn't inherit the MainWindow Resources, how that really works ?

class CustomClass:INotifyPropertyChanged
{
private string _test;
public string Test
{
get
{
return _test;
}
set
{
_test = value;
Notify("Test");
}
}
CustomClass()
{
this.Test = "";
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
private void Notify(string propName)
{
if(PropertyChanged!=null)
PropertyChanged(this,new PropertyChangedEventArgs(propName);
}
}
Use this class .I hope this will help.

Related

Usercontrol with a Dependency Property doesn't recognise changes

I have a custom class which a usercontrol has implemented as a dependency property in it's code behind.
public partial class HandControl
{
public HandControl()
{
InitializeComponent();
}
public Seat Seat
{
get
{
return (Seat)GetValue(SeatProperty);
}
set
{
SetValue(SeatProperty, value);
}
}
public static readonly DependencyProperty SeatProperty = DependencyProperty.Register("Seat", typeof(Seat), typeof(HandControl), new PropertyMetadata(null));
}
In my case I've bound the name property in that class to a label inside the usercontrols xaml.
<Label Content="{Binding Seat.Player.Name, RelativeSource={RelativeSource AncestorType={x:Type controls:HandControl}}}"/>
The view model of my window contains the property SeatTl and the xaml is binding to it:
public Seat SeatTr
{
get { return _seatTr; }
private set
{
_seatTr = value;
OnPropertyChanged();
}
}
<customControls:HandControl Grid.Row="1"
Grid.Column="3"
Seat="{Binding SeatTr}" />
However, when I change my class content (the name property) and manually raise OnPropertyChanged in my viewmodel (not the usercontrol), the label is not updated and still has the same content.
private void OnSeatChanged(Player player, SeatPosition seatPosition)
{
//... doing the changes ...\\
OnPropertyChanged("SeatTr");
}
Whats my problem? Anyone got a clue?
I think u should raise OnPropertyChanged for Seat.Player.Name property as It is being chaged.

How can I refresh a combobox after modifying its ItemsSource ObservableCollection

The problems is simple: when ItemsSource is updated Combobox doesn't "refresh" e.g. new items don't appear to be added to the list of items in the combobox.
I've tried the solution from aceepted answer to this question: WPF - Auto refresh combobox content with no luck.
here's my code,
XAML:
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
ViewModel:
public ObservableCollection<XmlNode> LeadTypeCollection { get; set; }
the way I update this collection is in the separate method, which loads data from updated XML file: this.LeadTypeCollection = GetLeadTypesDataSource();
I've also tried using Add for testing purposes:
this.LeadTypeCollection = GetLeadTypesDataSource();
ItemToAdd = LeadTypeCollection[LeadTypeCollection.Count - 1];
this.LeadTypeCollection.Add(ItemToAdd);
the code updating collection definitely kicks off, I can see new items in this collection when debugging, but I don't see them in the combobox.
Doing this in the xaml code-behind works: LeadTypeComboBox.ItemsSource = MyViewModel.GetLeadTypesDataSource(); but I'd like to achieve this with MVVM, i.e. the code must be in ViewModel which isn't aware of LeadTypeComboBox control.
Firedragons answer would work, but i would prefer to initialize the LeadTypeCollection just once and use clear, add remove to update your collection.
var update = GetLeadTypesDataSource();
this.LeadTypeCollection.Clear();
foreach(var item in update)
{
this.LeadTypeCollection.Add(item);
}
your xaml binding should work if the datacontext is right
<ComboBox Name="LeadTypeComboBox" ItemsSource="{Binding LeadTypeCollection}" />
I think I have seen this before and the solution was to update the collection property to raise the change.
i.e.
public class MyViewModel : INotifyPropertyChanged
{
private ObservableCollection<XmlNode> leadTypeCollection;
public string LeadTypeCollection
{
get { return leadTypeCollection; }
set
{
if (value != leadTypeCollection)
{
leadTypeCollection = value;
NotifyPropertyChanged("LeadTypeCollection");
}
}
public MyViewModel()
{
leadTypeCollection = new ObservableCollection<XmlNode>();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
PropertyChanged.Raise(this, info);
}
}
I have an extension method for raising the property (as found elsewhere on stackoverflow):
public static void Raise(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
if (null != handler)
{
handler(sender, new PropertyChangedEventArgs(propertyName));
}
}
A simple method is to change ItemsSource with empty list and then change it back to your updated source. A snippet from my project which is working:
RulesTable.ItemsSource = Rules.rulesEmpty;
RulesTable.ItemsSource = Rules.Get();

How to Databind to a CLR object with Source different to path

I am trying to update a textblock on the view by databinding to a property in the viewmodel (the datacontext for the view).
In the code below; when SelectedItem changes, I want the textblock text to update with the value of the Name property on SelectedItem.
In an attempt to achieve this I have set the binding source to the property that is changing and the binding path to the data I want to update the textblock with.
I.e. I am expecting that the binding engine will see a change on the binding Source (SelectedItem) and pull the data from the binding Path (SelectedItem.Name).
http://msdn.microsoft.com/en-us/library/ms746695.aspx
Setting the SelectedItem raises INPC but the text does not update.
public class ViewModel
{
public IConfiguration Configuration { get; set;}
}
public class Configuration : IConfiguration, INotifyPropertyChanged
{
public Item SelectedItem
{
get { return _item;}
set
{
_item = value;
ItemName = _item.Name;
RaisePropertyChangedEvent("SelectedItem");
}
}
public string ItemName
{
get { return _itemName;}
set
{
_itemName= value;
RaisePropertyChangedEvent("ItemName");
}
}
}
public class Item
{
public string Name { get; set;}
}
I know that changes on Configuration are seen because this works:
<TextBlock Text="{Binding Configuration.ItemName}"/>
But this does not:
<TextBlock Text="{Binding Path=Name, Source=Configuration.SelectedItem}"/>
And nor does this:
<TextBlock Text="{Binding Path=Configuration.SelectedItem.Name, Source=Configuration.SelectedItem}"/>
I'm assuming that this should be straightforward - what have I missed?
I've never actually seen anyone use Binding.Source before, so I don't know much about it. But my guess is that it's not dynamic. When you create your binding, it's grabbing a reference to the object specified in your Source, and then that's it: it uses that same reference for the lifetime of the binding.
Why make this complicated? Just use Path. That's the normal way of doing binding, and it's dynamic all the way -- what you're doing is exactly what Path is intended for.
<TextBlock Text="{Binding Path=Configuration.SelectedItem.Name}"/>
This is probably working, you just can not see it. The Binding engine has not been notified that the Name property of the Item object has changed.
Try implementing the INotifyPropertyChanged interface on the Item class as well (raising the PropertyChanged event as necessary)
This will work for your third binding situation, and also for a similar definition as below
<TextBlock DataContext="{Binding Path=Configuration.SelectedItem}" Text="{Binding Path=Name}"/>
But for a simpler fix, this should work:
<TextBlock Text="{Binding Path=Configuration.SelectedItem.Name}" />
Edit:
public class Configuration : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private Item _SelectedItem = null;
public Item SelectedItem
{
get
{
return _SelectedItem;
}
set
{
_SelectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
}
public class Item
{
public string Name { get; set; }
}
Then in a Command Execute somewhere I have this:
Configuration.SelectedItem = new Item() { Name = "test" };
Which updates the TextBlock in the View fine:
<TextBlock Text="{Binding Path=Configuration.SelectedItem.Name}" />

WPF: Nested DependencyProperties

I have an ObservableCollection of "Layouts" and a "SelectedLocation" DependencyProperty on a Window. The SelectedLocation has a property called "Layout", which is an object containing fields like "Name" etc. I'm trying to bind a combobox to the SelectedLayout but it's not working.
The following does not work, I've tried binding to SelectedItem instead to no avail. I believe it may be something to do with the fact that I'm binding to a subProperty of the SelectedLocation DependencyProperty (though this does implement INotifyPropertyChanged.
<ComboBox Grid.Row="2" Grid.Column="0" x:Name="cboLayout" ItemsSource="{Binding Layouts,ElementName=root}" SelectedValue="{Binding SelectedLocation.Layout.LayoutID,ElementName=root}" DisplayMemberPath="{Binding Name}" SelectedValuePath="LayoutID" />
However, the following works (Also bound to the "SelectedLocation" DP:
<TextBox Grid.Row="4" Grid.Column="1" x:Name="txtName" Text="{Binding SelectedLocation.Name,ElementName=root,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
What type property Layouts has? I suppose something like this this: IEnumerable<Layout>.
But you bind selected value to Layout.LayoutID. So you got situation, when combo box contains Layout objects, and you try to select it by Int identifier. Of course binding engine can't find any Int there.
I have no idea about details of your code, so one thing I could propose: try to reduce your binding expression: SelectedItem="{Binding SelectedLocation.Layout,ElementName=root}.
If no success, provide more code to help me understand what's going on.
====UPDATE====
As I've said, you are obviously doing something wrong. But I am not paranormalist and couldn't guess the reason of your fail (without your code). If you don't want to share your code, I decided to provide simple example in order to demonstrate that everything works. Have a look at code shown below and tell me what is different in your application.
Class Layout which exposes property LayoutId:
public class Layout
{
public Layout(string id)
{
this.LayoutId = id;
}
public string LayoutId
{
get;
private set;
}
public override string ToString()
{
return string.Format("layout #{0}", this.LayoutId);
}
}
Class SelectionLocation which has nested property Layout:
public class SelectedLocation : INotifyPropertyChanged
{
private Layout _layout;
public Layout Layout
{
get
{
return this._layout;
}
set
{
this._layout = value;
this.OnPropertyChanged("Layout");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
var safeEvent = this.PropertyChanged;
if (safeEvent != null)
{
safeEvent(this, new PropertyChangedEventArgs(name));
}
}
}
And Window class with dependency properties (actually, in my example StartupView is UserControl, but it doesn't matter):
public partial class StartupView : UserControl
{
public StartupView()
{
InitializeComponent();
this.Layouts = new Layout[] { new Layout("AAA"), new Layout("BBB"), new Layout("CCC") };
this.SelectedLocation = new SelectedLocation();
this.SelectedLocation.Layout = this.Layouts.ElementAt(1);
}
public IEnumerable<Layout> Layouts
{
get
{
return (IEnumerable<Layout>)this.GetValue(StartupView.LayoutsProperty);
}
set
{
this.SetValue(StartupView.LayoutsProperty, value);
}
}
public static readonly DependencyProperty LayoutsProperty =
DependencyProperty.Register("Layouts",
typeof(IEnumerable<Layout>),
typeof(StartupView),
new FrameworkPropertyMetadata(null));
public SelectedLocation SelectedLocation
{
get
{
return (SelectedLocation)this.GetValue(StartupView.SelectedLocationProperty);
}
set
{
this.SetValue(StartupView.SelectedLocationProperty, value);
}
}
public static readonly DependencyProperty SelectedLocationProperty =
DependencyProperty.Register("SelectedLocation",
typeof(SelectedLocation),
typeof(StartupView),
new FrameworkPropertyMetadata(null));
}
XAML of StartupView:
<UserControl x:Class="Test.StartupView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:self="clr-namespace:HandyCopy"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Root">
<WrapPanel>
<ComboBox ItemsSource="{Binding Path=Layouts,ElementName=Root}"
SelectedItem="{Binding Path=SelectedLocation.Layout, ElementName=Root}"/>
</WrapPanel>
</UserControl>

Setting and displaying a property in a WPF UserControl

Am i missing something here? I have created a usercontrol with a property and for arguments sake it has a text box in it.
<UserControl x:Class="Isd.Utility.SystemMonitorWpf.Bar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock x:Name="txtExpected" Grid.Column="0" Grid.ColumnSpan="2" Width="auto" Height="auto" FontSize="10" LayoutTransform="{StaticResource Rotate}" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Tahoma" Foreground="Red" Panel.ZIndex="100" Margin="5,5,5,5"/>
Then in the code behind i have
public partial class Bar : UserControl
{
private string _PropTest;
public string PropTest
{
get { return _PropTest; }
set { _PropTest = value; }
}
public Bar()
{
InitializeComponent();
txtExpected.Text = PropTest;
}
}
Then i drop the usercontrol into the xaml and set the property to a value
<local:Bar PropTest="test"></local:Bar>
In this example, when the usercontrol is displayed the text is showing as null, its like the property PropTest never got set. Am I missing something obvious here? Thanks in advance.
When used as an attribute like you have it, PropTest gets set after the constructor is called, so it doesn't get set when you apply the property to the text box.
You'd be better attaching an event to the property changing, or use the TextBox as the backing value for the property.
It's because the value of the attribute will never set on the Text-Property of the txtExpected-Control. At the time when the constructor is called, the property PropTest still null.
So, you have to change the implementation of your property:
public string PropTest
{
get { return txtExpected.Text; }
set { txtExptected.Text = value; }
}
You should use DependencyProperties, so you can bind your control properties via xaml
On your class declaration:
public static readonly DependencyProperty MyProperty = DependencyProperty.Register(
"MyProperty", //Property name
typeof(string), //Property type
typeof(MyControl), //Type of the dependency property provider
new PropertyMetadata(MyPropertyChanged));//Callback invoked on property value has changes
public string MyProperty
{
set
{
this.SetValue(MyProperty, value);
}
get
{
return (string)this.GetValue(MyProperty);
}
}
private static void MyPropertyChanged( object sender, DependencyPropertyChangedEventArgs args )
{
// update your control inner elements properties
}
Edited a few times because of typos :P
You don't appear to be doing anything in the setter of PropTest. It won't be set prior to construction, so it will be null when you do:
txtExpected.Text = PropTest;
Inside your constructor. If you do this:
public string PropTest
{
get { return _PropTest; }
set
{
_PropTest = value;
txtExpected.Text = PropTest;
}
}
It should work. It's not what I'd call an "ideal" way to do things though, you might want to take a look at Dependency Properties, INotifyPropertyChanged and Binding.
What happens when you add Text attribute like so:
<TextBlock x:Name="txtExpected" Text="{Binding PropTest}" />
and eliminate the line
txtExpected.Text = PropTest;
from the constructor?
Delegate value assignment in PropTest property to TextBox:
public string PropTest
{
get { return txtExpected.Text; }
set { txtExpected.Text = value; }
}

Resources