wpf привязывает элемент управления к коллекции - PullRequest
0 голосов
/ 04 октября 2010

Привет у меня проблема, у меня есть

   List<List<memoryCard>> 

, который я хочу показать в своем xmal в кнопке, как я могу привязать свою кнопку к данным, которые я хочу, это мой usercontrol:

<</p>

    <ControlTemplate x:Key="ButtonControlTemplate1" TargetType="{x:Type Button}">
    <Grid>
  <!--i think this is the place where i make mistake :-->
            <TextBlock Text="{Binding Path=CardWasfounded}"/>
            <Rectangle Margin="4,5,8,2" Stroke="Black" RadiusX="45" RadiusY="45" StrokeThickness="3"/>
    </Grid>
    </ControlTemplate>

    <DataTemplate x:Key="DataTemplate_Level2">
        <Button Content="{Binding}" Height="40" Width="50" Margin="4,4,4,4"  Template="{DynamicResource ButtonControlTemplate1}"/>
    </DataTemplate>

<DataTemplate x:Key="DataTemplate_Level1">
    <ItemsControl ItemsSource="{Binding }" ItemTemplate="{DynamicResource DataTemplate_Level2}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</DataTemplate>

Я хочу, чтобы каждая кнопка имела привязку к этой карте памяти

 class memoryCard : INotifyPropertyChanged
{
    #region c'tor
    public memoryCard(Brush _buttonColor)
    {
        buttonColor=_buttonColor;
    }
    #endregion

    #region allReadyFoundedCard

    bool cardWasfounded = false;
        public bool CardWasfounded
        {
            get
            {
                return cardWasfounded;
            }
            set
            {
                if (cardWasfounded != value)
                {
                    cardWasfounded = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this,
                        new PropertyChangedEventArgs("cardWasfounded"));

                    }
                }
            }
        }
        #endregion 

    #region colorofbutton
        string name = "sdasdas";
        public Brush buttonColor;
        public Brush ButtonColor
        {
            get
            {
                return buttonColor;
            }
            set
            {
                if (buttonColor != value)
                {
                    buttonColor = value;
                    if (PropertyChanged != null) PropertyChanged(this,
                        new PropertyChangedEventArgs("buttonColor"));
                }
            }
        }
        #endregion

    #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        #endregion
}

кого я хочу привязать к одной из моих сеток следующим образом:

используя этот класс главного окна:

 public MainWindow()
    {
        List<List<memoryCard>> lsts = new List<List<memoryCard>>();

        for (int i = 0; i < 5; i++)
        {
            lsts.Add(new List<memoryCard>());

            for (int j = 0; j < 5; j++)
            {
                lsts[i].Add(new memoryCard(Brushes.Green));
            }
        }

        InitializeComponent();

        lst.ItemsSource = lsts; 
    }

Ответы [ 2 ]

1 голос
/ 04 октября 2010

Хорошо, так что из того, что я собрал, у вас есть коллекция коллекций пользовательского типа данных, которая содержит цвет, который вы хотите связать.

Итак, вот небольшая демонстрация, которую вы (надеюсь) сможете расширить.

XAML:

<ItemsControl ItemsSource="{Binding Path=MyCollection}" 
              Height="300" Width="600">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Expander Header="Open Me">
                <ItemsControl DataContext="{Binding}" ItemsSource="{Binding}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Button DataContext="{Binding}"
                                    Background="{Binding Path=ButtonColor}"
                                    Content="{Binding Path=CardWasFounded}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Expander>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

И в коде позади:

public ObservableCollection<List<memoryCard>> MyCollection {get; set;}

public MainWindow()
{
    DataContext = this;
    MyCollection = new ObservableCollection<List<memoryCard>>();

    for (int i = 0; i < 5; i++)
    {
        List<memoryCard> list = new List<memoryCard>();

        for (int j = 0; j < 5; j++)
        {
            list.Add(new memoryCard(Brushes.Green));
        }
        MyCollection.Add(list);
    }

    InitializeComponent();
}

Это похоже на то, что вы пытаетесь сделать?

0 голосов
/ 04 октября 2010

Когда вы вызываете событие PropertyChanged, ваше имя параметра (строка, которую вы передаете в аргументах события) должно совпадать с точно со свойством, к которому вы привязаны.Это включает в себя чувствительность к регистру.

Вы делаете new PropertyChangedEventArgs("buttonColor"), когда свойство фактически ButtonColor.Это заставит систему привязки WPF игнорировать событие (поскольку она определяет, что у нее нет соответствующей привязки, поэтому она не должна ничего делать).У вас та же проблема с CardWasFounded

...