简体   繁体   中英

Using custom class as ItemsControl Tag in WPF XAML?

I have a web app built with ASP.NET and React. I'm trying to port some components to a Windows WPF app, and this is my first time using WPF/XAML. My experience with XAML hasn't been too bad... it's like a more-verbose React, but one thing I can't work out how to do properly is save bind parameters from nested lists to ItemsControl.

In React, I'd use something like onClick=“(e)=>this.myFunction(e, parentIndex)” , so that I could send 2 parameters at once, maybe representing an index and a value, or a childIndex and parentIndex, etc.

It is unclear to me how to properly do this with WPF's flavour of XAML, and XAML in general. From what I've read, I have to use a ICommand (which I feel like is overkill, as the params I'm using are usually not user-input, and instead are references to other objects on the back-end) or set the tag of the initiating object (a button) to a custom class with the amount of attributes I need.

The second approach seems more sensible to me, but I can't work out how to dynamically do this with an ItemsControl on the XAML frontend — all the tutorials I've seen do this in the codebehind, which I don't think is possible as I'm using an ItemsControl.

How can I do this?

You can pass item to command via CommandParameter. For assign command to mouseEvents you can use InputBindings.

Lets assume that you have ViewModel with command

public ICommand SomeClickCommand {get; private set}

public void SomeCLickCOmmandHandler (object parameter)
{
      var yourItem = object as SomeItemType;
}

you can assign item to command in DataTemplate

<DataTemplate TargetType={x:Type someItemType}>
    <Border>
       <Border.InputBindings>
               <MouseBinding Command="{Binding Path=DataContext.SomeClickCommand , RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}, Mode=FindAncestor}}"
                   CommandParameter="{Binding}"
                   Gesture="LeftDoubleClick" />
        </Border.InputBindings>

        <TextBlock Text={Binding SomeProperty} />
     </Border>
</DataTemplate>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM