我正在使賓果卡生成器嘗試瞭解更多有關WPF的信息,並且無法確定如何設置標籤內容屬性以便從屬性中設置我的代碼隱藏文件。將標籤的內容綁定到代碼隱藏文件中的屬性
我以爲我可以使用
<Setter Property="Content" Value="{Binding BNumber}">
的內容屬性標籤的內容設置爲我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>();
謝謝你你的quic k響應O_O如果我明白這個權利,'this.DataContext = this;'是將Window對象的DataContext屬性設置爲..本身? – Zack
這是正確的:)你通常會將DataContext設置爲ViewModel對象,但使用Window對於學習/試驗綁定而言是很好的。 –
我跟着ssdam的建議,並使用UniformGrid的顯示在ItemsControl中隨機選擇的數字,我有[另一個問題](http://stackoverflow.com/q/14282440/1804496)關於訪問項目本身,如果你有一個時刻 – Zack