in THIS code , binding not work:
- <Window x:Class="WpfApplication6.Window2"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:l="clr-namespace:WpfApplication6"
- Title="Window2" Height="300" Width="300">
- <Grid>
- <StackPanel>
- <Button Height="50" Width="100" Click="Button_Click_1">
- <l:Item val="{Binding ElementName=aaa,Path=Text,Mode=TwoWay}" />
- </Button>
- <Button Height="50" Margin="30" Click="Button_Click">
- <l:ItemList>
- <l:ItemList.MyList>
- <l:Item val="{Binding ElementName=aaa, Path=Text, Mode=TwoWay}" />
- <l:Item val="{Binding ElementName=bbb, Path=Text, Mode=TwoWay}" />
- </l:ItemList.MyList>
- </l:ItemList>
- </Button>
- <TextBlock Text="aaa" Name="aaa" />
- <TextBlock Text="bbb" Name="bbb"/>
- </StackPanel>
- </Grid>
- </Window>
c#:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Data;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using System.Windows.Shapes;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
-
- namespace WpfApplication6
- {
-
-
-
- public partial class Window2 : Window
- {
- public Window2()
- {
- InitializeComponent();
- }
-
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- ItemList il = (((Button)sender).Content) as ItemList;
- MessageBox.Show(il.MyList[0].val);
- }
-
- private void Button_Click_1(object sender, RoutedEventArgs e)
- {
- Item i = (((Button)sender).Content) as Item;
- MessageBox.Show(i.val.ToString());
- }
-
-
- }
-
- public class ItemList : Control
- {
- public ObservableCollection<Item> MyList
- {
- get { return (ObservableCollection<Item>)GetValue(MyListProperty); }
- set { SetValue(MyListProperty, value); }
- }
- public static readonly DependencyProperty MyListProperty =
- DependencyProperty.Register("MyList", typeof(ObservableCollection<Item>), typeof(ItemList), new UIPropertyMetadata(new ObservableCollection<Item>()));
- }
-
- public class Item : FrameworkElement
- {
- public string val
- {
- get { return (string)GetValue(valProperty); }
- set { SetValue(valProperty, value); }
- }
- public static readonly DependencyProperty valProperty =
- DependencyProperty.Register("val", typeof(string), typeof(Item), new UIPropertyMetadata(null,onChange));
-
- private static void onChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
- {
- }
- }
-
- }
error msg:
System.Windows.Data Error: 4 :
Cannot find source for binding with reference 'ElementName=aaa'.
BindingExpression:Path=Text; DataItem=null; target element is 'Item' (Name=''); target property is 'val' (type 'String')
Does anyone know why it does not work?
Thanks