简体   繁体   中英

How can I get content of an button in my ViewModel via RelayCommand (mvvmlight)

i dont know how to get the Content of an Button (for examle if an button has the content "press me" i want this to have on my viewmodel as a string).

I already tried to send it via messaging service and via command parameter but it didnt work...

this is my xaml:

<Button x:Name="btn">
                            <Button.Content>
                                <StackPanel Orientation="Horizontal">
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition></RowDefinition>
                                            <RowDefinition></RowDefinition>
                                        </Grid.RowDefinitions>
                                        <TextBlock Grid.Row="1" x:Name="product" Text="{Binding Artikel}" ></TextBlock>
                                    </Grid>
                                </StackPanel>
                            </Button.Content>
                        </Button>

And i want the value of the button (the text of the textblock) -> "product" in my viewmodel as a string

I hope u can help me, thanks in advance!!

EDIT:

this is my Command binded to my Button and i have no clue how to implement the CanExecute Method...

 RelayCommand sendDataBtn;
    public RelayCommand SendDataBtn
    {
        get
        {
            if (sendDataBtn == null)
            {
                sendDataBtn = new RelayCommand(() =>
                {
                    if (Globals.isLoggedIn == true) {
                      //do smth
                    }
                    else
                    {

                        var msg = new OpenOrCloseCameraPage() { Name = "open" };
                        Messenger.Default.Send<OpenOrCloseCameraPage>(msg);
                    }

                });
            }
            return sendDataBtn;
        }
    }

You shouldn't have to pass the Text of the TextBlock as a command parameter since you are binding to Artikel , but if you want to do it anyway, you could bind to the TextBlock like this:

<Button x:Name="btn" Command="{Binding Command}" CommandParameter="{Binding Text, ElementName=product}">
    <Button.Content>
        <StackPanel Orientation="Horizontal">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>
                <TextBlock Grid.Row="1" x:Name="product" Text="{Binding Artikel}" ></TextBlock>
            </Grid>
        </StackPanel>
    </Button.Content>
</Button>

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