将TextBox名称参数从MainWindow.xaml传递到button_click函数

时间:2015-02-04 22:59:11

标签: c# wpf xaml

我正在制作一个使用Microsoft.Win32.OpenFileDialog的表单dlg = new Microsoft.Win32.OpenFileDialog();提供文件选择菜单。

我想使用相同的函数来更新输入文件的文本框和输出文件的文本框。

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Width="515" Height="96" VerticalAlignment="Top">
        <TextBlock Text="Input File:"  VerticalAlignment="Center"  />
        <TextBox x:Name="InputFileBox" Width ="213" VerticalAlignment="Center" TextChanged="InputFileBox_TextChanged" Height="17" Margin="0,39,0,40"  />
        <Button Content="Browse" Width="47" Margin="0,39,0,40" RenderTransformOrigin="1.599,0.714" Click="Browse_Click"/>
    </StackPanel>


    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Width="515" Height="96" VerticalAlignment="Top">
        <TextBlock Text="Output File:"  VerticalAlignment="Center"  />
        <TextBox x:Name="OutputFileBox" Width ="213" VerticalAlignment="Center" TextChanged="OutputFileBox_TextChanged" Height="17" Margin="0,39,0,40"  />
        <Button Content="Browse2" Width="47" Margin="0,39,0,40" RenderTransformOrigin="1.599,0.714" Click="Browse_Click"/>
    </StackPanel>

所以我希望能够发送&#34; InputFileBox&#34;或&#34; OutputFileBox&#34;使用&#34; BrowseClick&#34;这样我就不必拥有BrowseInputClick和BrowseOutputClick功能。

在Browse_Click函数中我希望能够做到这样的事情:

 private void Browse_Click(object sender, RoutedEventArgs e)
    {
        // Create OpenFileDialog 
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();


        // Display OpenFileDialog by calling ShowDialog method 
        Nullable<bool> result = dlg.ShowDialog();


        // Get the selected file name and display in a TextBox 
        if (result == true)
        {
            // Open document 
            string filename = dlg.FileName;

            // I don't know what to put here: input/outputTextBoxName = filename
        }

感谢

1 个答案:

答案 0 :(得分:2)

在WPF中,您可以设置按钮的标记属性。

完成后,您可以使用

在点击处理程序中获取标记属性

在XAML中,将Tag="input"添加为inputTextBox的一个属性,将Tag="output"添加到outputTextBox(例如:<TextBox x:Name="inputTextBox" Tag="input"/>

var tag = (sender as Button).Tag;

然后:

if (tag == 'input')
    inputTextBox.Text = filename;
else outputTextBox.Text = filename;