【问题标题】:Binding a Label's content to a property in code-behind file将标签的内容绑定到代码隐藏文件中的属性
【发布时间】: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&lt;String&gt; 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>();

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    将列表本身随机化可能比每个数字更容易,因为这将阻止重复。

    使用统一网格可能比添加一堆标签更容易。

    例子:

    Xaml:

    <Window x:Class="WpfApplication4.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="346" Width="300" Name="UI">
    
        <Grid DataContext="{Binding ElementName=UI}">
            <ItemsControl ItemsSource="{Binding BNumbers}" Margin="0,29,0,0">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Border Margin="1" BorderBrush="Black" BorderThickness="1" CornerRadius="2">
                             <Label Content="{Binding}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  />
                        </Border>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <UniformGrid Columns="5" Rows="5"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
            <Button Content="New" Height="23" HorizontalAlignment="Left" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        </Grid>
     </Window>
    

    代码:

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public List<string> AllNumbers { get; set; }
        private List<string> _bnumbers = new List<string>();
    
        public MainWindow()
        {
            InitializeComponent();
            AllNumbers = new List<string>();
            // Bingo game 75 numbers, 5x5 grid
            for (int i = 0; i < 75; i++)
            {
                AllNumbers.Add(i.ToString());
            }
        }
    
        public List<string> BNumbers
        {
            get { return _bnumbers; }
            set { _bnumbers = value; NotifyPropertyChanged("BNumbers"); }
        }
    
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            RandomizeList(AllNumbers);
            BNumbers = AllNumbers.Take(25).ToList();
        }
    
        private void RandomizeList<T>(IList<T> list)
        {
            Random rng = new Random();
            int n = list.Count;
            while (n > 1)
            {
                n--;
                int k = rng.Next(n + 1);
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
    

    结果(“New”会生成一个新游戏)

    【讨论】:

    • 非常感谢您花时间帮助我学习!我以前从未听说过统一网格,但听起来它会很完美,而且不会像我试图创建的那样混乱。
    • 我有another question,如果你愿意的话?
    【解决方案2】:

    在构造函数中,需要设置DataContext:

    this.DataContext = this;
    

    您还需要更改您的设置器以匹配属性名称 RandomBNumber :

    <Setter Property="Content" Value="{Binding RandomBNumber }">
    

    【讨论】:

    • 感谢您的快速回复 O_O 如果我理解正确,this.DataContext = this; 正在将 Window 对象的 DataContext 属性设置为.. 本身?
    • 没错 :) 您通常会将 DataContext 设置为 ViewModel 对象,但为了学习/实验绑定,使用 Window 也很好。
    • 我按照 ssdam 的建议使用 UniformGrid 来显示在 ItemsControl 中随机选择的数字,如果您有时间,我有 another question 自己访问这些项目
    猜你喜欢
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2010-12-16
    • 2012-02-04
    • 2019-06-07
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多