【发布时间】:2013-01-08 07:18:59
【问题描述】:
我正在制作一个宾果卡生成器以尝试了解有关 WPF 的更多信息,但在弄清楚如何设置标签内容属性以从我的代码隐藏文件中的属性中设置时遇到了麻烦。
我认为我可以使用
<Setter Property="Content" Value="{Binding BNumber}">
为content属性设置标签的内容为我List<String>的随机元素?
我的 MainWindow.xaml
中有<Window x:Class="Bingo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="600" Width="800"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid Width="350" Height="420" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="70" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="70" />
<ColumnDefinition Width="70" />
</Grid.ColumnDefinitions>
<!-- The Label I'm trying to set in this example -->
<Label Grid.Column="0" Grid.Row="1" Style="{StaticResource BNumber}"
FontSize="50" Width="70"/>
</Grid>
</Grid>
</Window>
我的 App.xaml 代码
<Application x:Class="Bingo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<Style TargetType="Label" x:Key="BNumber">
<Setter Property="Content" Value="{Binding}"></Setter>
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="Beige"/>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
在我的 MainWindow.xaml.cs 中,我有这个 List<String> BNumbers 对象和一个返回 BNumbers 列表的随机元素的属性
public MainWindow() {
InitializeComponent();
BNumbers.Add("1");
BNumbers.Add("2");
BNumbers.Add("3");
BNumbers.Add("4");
BNumbers.Add("5");
BNumbers.Add("6");
BNumbers.Add("7");
BNumbers.Add("8");
BNumbers.Add("9");
BNumbers.Add("10");
BNumbers.Add("11");
BNumbers.Add("12");
BNumbers.Add("13");
BNumbers.Add("14");
BNumbers.Add("15");
}
public string RandomBNumber {
get { return randomB(); }
}
public string randomB() {
Random rand = new Random();
int randomBNumber = rand.Next(0, 15);
return BNumbers[randomBNumber];
}
public List<String> BNumbers = new List<string>();
【问题讨论】: