Reputation:
How would I go about binding this in XAML?
I am looking to use an observable collection to populate a ListView
ever time a method is called which will be through a drop event on another control. The collection is getting added too but the ListView
won't populate.
I haven't been using WPF long so any insight would be great.
namespaceA
{
public class SomeClassA
{
public string FirstName { get; set; }
}
public class SomeClassB
{
public void MethodA()
{
ObservableCollection<SomeClassA> Name_Col = new ObservableCollection<SomeClassA>();
Name_col.Add(new SomeClassA { FirstName = "SomeValue" });
}
}
}
XAML:
<ObjectDataProvider
x:Key="Viewmodel"
ObjectType="{x:Type Local:NamespaceA}"/>
<ListView DataContext="{StaticResource Viewmodel}"
Height="396"
HorizontalAlignment="Left"
Margin="766,67,0,0"
Name="listView1"
VerticalAlignment="Top"
Width="260"
ItemsSource="{Binding Name_col}" />
Upvotes: 0
Views: 1562
Reputation: 132648
There are quite a few things wrong with your code
First off, your DataContext is pointing to a namespace, not an object. Change that to be an instance of an object.
<ObjectDataProvider x:Key="Viewmodel" ObjectType="{x:Type local:SomeClassB}"/>
Or
<local:SomeClassB x:Key="Viewmodel" />
Second, your ObservableCollection
is not a public property, so your View cannot see nor access it.
public class SomeClassB
{
public ObservableCollection<SomeClassA> Name_Col { get; set; }
public void MethodA()
{
Name_Col = new ObservableCollection<SomeClassA>();
Name_col.Add(new SomeClassA { FirstName = "SomeValue" });
}
}
And last of all, WPF bindings are case-sensitive so you need to fix the ItemsSource
binding to use the correct case
<ListView ...
ItemsSource="{Binding Name_Col}" />
Upvotes: 1
Reputation: 3972
The only things you can access in bindings are public
(internal
doesn't work) properties and indexers of public
classes.
And no matter how, variables declared inside a method will never be accessible from anywhere outside the said method. It's a common mistake people who used to work with scripting languages often make. To access something outside a method (or inside of another), that must be declared outside of the method.
One useful hint: Visual Studio's Output
window is a very useful tool for tracking binding errors.
On a side note: Bindings are case sensitive. Even if your code followed the rules mentioned above, WPF would still not find the binding source, as your binding path is Name_col
, but the property's name is Name_Col
.
Upvotes: 4
Reputation: 160
Assuming this code is pasted, your binding is looking at a nonexistent property. Try capitalizing the 'c' in your binding. Name_col -> Name_Col
Upvotes: 0