【发布时间】:2010-10-04 09:09:21
【问题描述】:
你好 我遇到了问题
List<List<memoryCard>>
我想在我的 xmal 中显示一个按钮,我怎样才能将我的按钮绑定到我想要的数据,这就是我的用户控件:
<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;
}
【问题讨论】:
-
在您的两个属性中,您在每个相应的设置器中复制 NotifyPropertyChanged(string info) 中的代码。
-
这是什么意思?这不是实施它的正确方法吗?
-
方法是对的,只是代码的重复。您已经设置了一个 NotifyPropertyChanged 方法来为您执行此操作,而不是检查每个 setter 中的属性更改是否为空。所以只需调用该方法即可。减少代码重复和臃肿。
-
好的,所以这不是我在这里遇到更大问题的重点:)
-
是的,我只是想让您知道,同时我正在为您制定解决方案。除了您提到按钮并且有一个按钮颜色属性,但在列出的 XAML 中没有任何地方引用实际按钮。但我想我明白你想要做什么。
标签: wpf wpf-controls binding