0

I have a list of devices and in that list user will select which COM port represents which device, each device has its own StackPanel shown below:

<StackPanel Orientation="Horizontal" Margin="5">
    <TextBlock Width="140"  Text="IMT" VerticalAlignment="Center"/>
    <ComboBox Width="250" Margin="0,0,40,0" x:Name="FM_list" SelectionChanged="DeviceSelected"/>
    <TextBlock x:Name="FM_selection" Margin="0,0,40,0" Width="80 "/>
    <Button Background="Red" Width="50" Click="Port_selected" x:Name="FM_selection1"/>
</StackPanel>

After user makes his selection in the ComboBox it is verified by clicking an adjecent Button.
I'd like it so that when the Button is clicked x:Name of the TextBlock (or an alternate way of referencing) is passed to the Port_selected function so I can get the correct device when calling TextBox.Name on the sender.

I could a seperate x:Name for each of those buttons and a dictionary to match which button matches which TextBlock and which StackPanel, but I'd like to know how to do without that workaround. Right now I just strip the last char of the Button's x:Name...

mega_creamery
  • 667
  • 7
  • 19
  • Instead of attaching a Click event handler, you could bind the Button's `Command` property to an ICommand property in a view model, and bind the Button's `CommandParameter` property to some other XAML element, which will then be passed as parameter to the command's CanExecute and Execute methods. E.g. like here: https://stackoverflow.com/q/12371253/1136211 – Clemens Jun 19 '19 at 13:44

1 Answers1

0

Port_selected is an event handler and you cannot pass a string value to this one.

If you are familiar with the MVVM design pattern there are better ways to solve this, for example using commands and command parameters, but the easiest solution given your current setup is probably to get a reference to the TextBlock in the event handler and then get the value of its Name property, e.g.:

private void Port_selected(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    StackPanel stackPanel = btn.Parent as StackPanel;
    if (stackPanel != null)
    {
        TextBlock textBlock = stackPanel.Children
            .OfType<TextBlock>()
            .FirstOrDefault(x => !string.IsNullOrEmpty(x.Name));
        if (textBlock != null)
        {
            string name = textBlock.Name;
            //...
        }
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thanks mm8, sorting me out with good solution for the n-th time. I never knew how to navigate up the xaml tree in the code so thanks for this aproach. – mega_creamery Jun 19 '19 at 14:07