【问题标题】:C# Eventhandler with parameter control type from xaml具有来自 xaml 的参数控制类型的 C# 事件处理程序
【发布时间】:2014-09-15 10:50:55
【问题描述】:

我想调用 onClick 事件并将 Textbox 对象从 .xaml 代码传输到事件处理程序。 这可能吗?

我会尝试说明,

这是我的 Main.xaml.cs 代码:

<Button x:Name="VideoTargetBtn" Content="Browse..." HorizontalAlignment="Left" VerticalAlignment="Top" Width="89"  Click="VideoTargetBtn_Click" Height="27" Margin="10,13,0,0"/>
<TextBox x:Name="videoTargetPathTxt" Height="27" TextWrapping="Wrap" VerticalAlignment="Top" IsReadOnly="True"  Margin="117,13,21,0"/>

这就是我想做的:

private void VideoTargetBtn_Click(object sender, RoutedEventArgs e, TextBox currTextbox)
{
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    bool? fileIsSelected = saveFileDialog.ShowDialog();
    if (fileIsSelected == true)
    {
        currTextbox.Text = saveFileDialog.FileName;
    }
}

【问题讨论】:

  • 一般来说,如果你在 WPF 中使用点击处理程序,你就做错了。
  • 这不是我的代码,我试图说明。
  • 不管是你的代码,它是错误的。您不应该在 WPF 期间使用单击处理程序。查找MVVMICommandWPF。这应该通过CommandCommandParameter={Binding ElementName=videoTargetPathTxt, Path=Text} 来实现。
  • @TalShaked 我实现了一个向您展示下面的 MVVM 模型的解决方案,它向您展示了一些很酷的技巧,并允许用户按 Enter 键来调用您的方法。为简单起见,我保留了 ViewModelLocator,因此将数据上下文设置在某处。 IE 用于在代码隐藏或直接在 xaml 中进行测试...或使用 viewmodellocator =)

标签: c# wpf xaml eventhandler


【解决方案1】:

如果您需要做的只是从后面的代码中访问控件,则只需按名称引用它,因为您在控件上使用了值为 videoTargetPathTxt 的 x:Name 属性。

让事件处理程序保持正常,并将您的代码替换为

if (fileIsSelected == true)
{
    videoTargetPathTxt.Text = saveFileDialog.FileName;
}

【讨论】:

  • 每个按钮与其他文本框。
【解决方案2】:

不,它不是,你不需要,

在私有 VideoTargetBtn_Click 处理程序中只检索文本框内容

videoTargetPathTxt.Text


private void VideoTargetBtn_Click(object sender, RoutedEventArgs e)
{
    SaveFileDialog saveFileDialog = new SaveFileDialog();

    bool? fileIsSelected = saveFileDialog.ShowDialog();

    if (fileIsSelected == true)
    {
        videoTargetPathTxt.Text = saveFileDialog.FileName;
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 2011-09-05
    • 2019-05-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    相关资源
    最近更新 更多