80255

Binding doesn't work when using custom control in DataTemplate

I'm trying to replace a standard control inside ListView DataTemplate with a custom control, but binding doesn't seem to work properly. Here is the definition of the ListView:

<Grid> <ListView ItemsSource="{Binding DataItemsCollection}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="Static text" /> <TextBlock Text="{Binding DataItemText}" /> <BindingTest:CustomControl CustomText="{Binding DataItemText}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid>

Where DataItemsCollection is an observable collection of type

public class DataItemClass : INotifyPropertyChanged { string _dataItemText; public string DataItemText { get { return _dataItemText; } set { _dataItemText = value; Notify("DataItemText"); } } public event PropertyChangedEventHandler PropertyChanged; public void Notify(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }

And main window code looks like this:

public partial class MainWindow : Window { public ObservableCollection<DataItemClass> _dataItemsCollection = new ObservableCollection<DataItemClass> { new DataItemClass { DataItemText = "Test one" }, new DataItemClass { DataItemText = "Test two" }, new DataItemClass { DataItemText = "Test three" } }; public ObservableCollection<DataItemClass> DataItemsCollection { get { return _dataItemsCollection; } } public MainWindow() { InitializeComponent(); DataContext = this; } }

Custom control is simple:

<StackPanel Orientation="Horizontal"> <Label Content="Data Item:" /> <TextBlock Text="{Binding CustomText, Mode=OneWay}" /> </StackPanel>

With CustomText defined as

public static DependencyProperty CustomTextProperty = DependencyProperty.Register( "CustomText", typeof(string), typeof(CustomControl), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public string CustomText { get { return (string)GetValue(CustomTextProperty); } set { SetValue(CustomTextProperty, value); } }

When I run this project I see correct text in second TextBlock in DataTemplate, but not inside of a custom control. What am I doing wrong?

Answer1:

By default Binding is relative to DataContext, which is DataItemClass in your case, but CustomText property is declared in CustomControl. You need to specify relative binding source:

<TextBlock Text="{Binding Path=CustomText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=BindingTest:CustomControl}}" />

If your control is going to stay that simple, you can completely remove CustomText property and change <TextBlock Text="{Binding CustomText, Mode=OneWay}" /> to just <TextBlock Text="{Binding DataItemText} />.

Recommend

  • Spring boot 2.0.0.M4 required a bean named 'entityManagerFactory' that could not be found
  • Multicolored edittext hint
  • c# open webrowser in many tab
  • Django invalid literal for int() with base 10
  • Bypass multiple inheritance in Java
  • saving file generated by TCPDF
  • WPF Visiblity Binding to Boolean Expression with multiple Variables
  • How does document.ready work with angular element directives?
  • how to find common suffix in java by using method
  • Problems compiling files using JOGL
  • Webgrid not refreshing after delete MVC
  • QLPreviewController hide print button in ios6
  • Swing - Get new component under mouseReleased
  • Refering to the class itself from within a class mehod in Objective C
  • Java: can you cast Class into a specific interface?
  • FileReader+canvas image loading problem
  • Using jQuery closest() method with class selector
  • Insert into database using onclick function
  • Can I display google adwords (AdView) in javafx on android
  • Align navbar back button on right side
  • How to add date and time under each post in guestbook in google app engine
  • How to set/get protobuf's extension field in Go?
  • DirectX11 ClearRenderTargetViewback with transparent buffer?
  • Validaiting emails with Net.Mail MailAddress
  • sending/ receiving email in Java
  • How to set my toolbar fixed while scrolling android
  • Web-crawler for facebook in python
  • Akka Routing: Reply's send to router ends up as dead letters
  • AT Commands to Send SMS not working in Windows 8.1
  • Cannot Parse HTML Data Using Android / JSOUP
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • JTable with a ScrollPane misbehaving
  • Java static initializers and reflection
  • apache spark aggregate function using min value
  • unknown Exception android
  • Sorting a 2D array using the second column C++
  • Observable and ngFor in Angular 2
  • failed to connect to specific WiFi in android programmatically
  • Unable to use reactive element in my shiny app
  • How can I use threading to 'tick' a timer to be accessed by other threads?