将一组按钮链接到一组标签

时间:2011-12-19 10:08:03

标签: c# wpf

我正在读取XML文件并使用它来填充WPF表单。 XML文件中的每个条目都用于创建按钮和标签。

我遇到的问题是将按钮与标签相关联:

这是我的代码:

// Loop through Backups
foreach (var back in backups)
{
    // Create Wrap Panel
    myWrapPanel = new WrapPanel();
    //myWrapPanel.Background = System.Windows.Media.Brushes.Red;
    myWrapPanel.Orientation = System.Windows.Controls.Orientation.Horizontal;
    myWrapPanel.Width = 600;
    myWrapPanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
    myWrapPanel.VerticalAlignment = System.Windows.VerticalAlignment.Top;

    // **************************************
    // Add Controls to Wrap Panel
    // **************************************
    // Backup Source
    System.Windows.Controls.Button btnBackupSource = new System.Windows.Controls.Button();
    btnBackupSource.Content = "Source";
    btnBackupSource.Height = 25;
    btnBackupSource.Width = 75;
    btnBackupSource.Click += btnBackupSource_Click;
    btnBackupSource.Name = "btnBackupSource";
    myWrapPanel.Children.Add(btnBackupSource);

    System.Windows.Controls.Label lblBackupSource = new System.Windows.Controls.Label();
    lblBackupSource.Height = 25;
    lblBackupSource.Width = 461;
    lblBackupSource.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
    lblBackupSource.VerticalAlignment = System.Windows.VerticalAlignment.Top;
    lblBackupSource.Name = "lblBackupSource";
    lblBackupSource.Content = "";
    myWrapPanel.Children.Add(lblBackupSource);

按钮和标签创建正常,但我很难将它们相互关联。例如,当按下按钮时,结果需要出现在与按钮相关联的单个标签中。

非常欢迎任何关于如何进行的建议!

我目前得到的是每个按钮更新一个标签:

private void btnBackupSource_Click(object sender, RoutedEventArgs e)
    {
        SourceFolderBrowser = new System.Windows.Forms.FolderBrowserDialog();
        // Allow users to creating new folders and default to the my documents folder.
        SourceFolderBrowser.ShowNewFolderButton = true;
        SourceFolderBrowser.RootFolder = Environment.SpecialFolder.Personal;

        SourceFolderBrowser.ShowDialog();

        label2.Content = SourceFolderBrowser.SelectedPath;
    }

然而,我要做的是让每个按钮更新其相关标签。

2 个答案:

答案 0 :(得分:2)

以下是我的建议:

将要关联的标签与按钮的Tag属性中的按钮相关联,如下所示:

btnBackupSource.Tag = lblBackupSource;

稍后当您在有线电话btnBackupSource_Click中执行某些操作时,您可以这样做:

var button = sender as Button;
var label = button.Tag as Label;
label.Text = "Hello";

答案 1 :(得分:0)

通过创建DataTemplate并将ListBox.ItemTemplate设置为使用DataTemplate,这将更加容易。

这样您就不必在代码中创建所有控件,只需连接按钮并标记一次(最好通过数据绑定)。

<Window.Resources>
    <DataTemplate x:Key="backupView">
        <StackPanel Orientation="Horizontal">
            <Label Content="{Binding BackupName}"/>
            <Button Content="Source" Command="{Binding DoSomethingCommand}" />
        </StackPanel>
    </DataTemplate>
</Window.Resources>


<ListBox ItemsSource="{Binding}" ItemTemplate="{StaticResource backupView}"/>

在代码中,您需要使用属性Name和DoSomethingCommand创建一个类(Backup?)。此命令将修改备份名称,并自动传递给视图。