Как получить содержимое кнопок в качестве свойства в вызываемом всплывающем окне в приложении UWP? - PullRequest
0 голосов
/ 10 мая 2019

USECASE

У меня есть набор (8) кнопок, которые открывают эстакаду с помощью свойства set style.

Эстакада содержит кнопку «Применить». Кнопка запускает команду, которая выполняет в модели представления что-либо, связанное с содержимым кнопок источника (от 1 до 8).

Задача

Как получить значение содержимого моей кнопки, которая запускает эстакаду для моей команды?

Я думал, что CommandParameter={Text ElementName=Source} должен делать то, что я хочу, но нет, это не так.

Ресурсы

<Style x:Key="PixelButtonStyle" TargetType="Button">
    <Setter Property="Width" Value="50" />
    <Setter Property="Height" Value="50" />
    <Setter Property="Margin" Value="5" />
    <Setter Property="Flyout" Value="{StaticResource PixelColorPickerFlyOut}" />
</Style>

<Flyout x:Key="PixelColorPickerFlyOut">
            <StackPanel>
                <!-- Picker -->
                <ColorPicker x:Name="PixelColorPicker"
                             IsAlphaEnabled="False"
                             IsColorChannelTextInputVisible="False"
                             IsAlphaSliderVisible="False"
                             IsAlphaTextInputVisible="False"
                             IsHexInputVisible="False"
                             IsColorSliderVisible="False"
                             Width="300"/>

                <!-- Button row -->
                <StackPanel Orientation="Horizontal" 
                            Margin="0 20 0 0">
                    <Button Content="Apply"
                            Width="100"
                            Margin="0 0 10 0"
                            Command="{Binding ApplyColorCommand}"/>

                    <Button Content="Cancel"
                            Width="100"/>

                    <TextBlock Text="{Binding Path=Source}" />
                </StackPanel>
            </StackPanel>
        </Flyout>

Usage

<Button Style="{StaticResource PixelButtonStyle}" Content="" />

Обновление 1

Я также пытался использовать в качестве всплывающей кнопки:

<Button Command="{Binding ElementName=Grid, Path=DataContext.ApplyColorPickerCommand}" 
        Content="Apply" />

и кнопка, запускающая всплывающее окно:

<Button Style="{StaticResource PixelButtonStyle}" 
        DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}" 
        Content="1" 
        Background="Green"/>

но это не имело положительного эффекта.

1 Ответ

1 голос
/ 13 мая 2019

Я не уверен, правильно ли я понимаю ваш запрос. Вы действительно имеете в виду это, у вас есть 8 кнопок, и каждая из них может поднять всплывающее окно. Итак, вы хотите знать, какая кнопка на самом деле подняла всплывающее окно? Если это то, что вы хотите, возможно, вы можете попробовать следующий код:

Во-первых, у каждого FramewrokElement есть свойство tag. Итак, вот демо XAML:

 <Grid>
    <Button Tag="button no.1" Command="{Binding MyBtnClickCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=Tag}" Content="set empty content"/>
</Grid>

Тогда, если вы используете RelayCommand, мы можем получить значение тега из этого класса:

 public class RelayCommand : ICommand
{
    private readonly Action _execute;
    private readonly Func<bool> _canExecute;
    /// <summary>
    /// Raised when RaiseCanExecuteChanged is called.
    /// </summary>
    public event EventHandler CanExecuteChanged;
    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action execute)
        : this(execute, null)
    {
    }
    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action execute, Func<bool> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }
    /// <summary>
    /// Determines whether this RelayCommand can execute in its current state.
    /// </summary>
    /// <param name="parameter">
    /// Data used by the command. If the command does not require data to be passed,
    /// this object can be set to null.
    /// </param>
    /// <returns>true if this command can be executed; otherwise, false.</returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute();
    }
    /// <summary>
    /// Executes the RelayCommand on the current command target.
    /// </summary>
    /// <param name="parameter">
    /// Data used by the command. If the command does not require data to be passed,
    /// this object can be set to null.
    /// </param>
    /// 
    **private string btntag;
    public string BtnTag
    {
        get { return btntag; }
        set { btntag= value; }
    }**


    public void Execute(object parameter)
    {
         **btntag= parameter as string;**
        _execute();
    }
    /// <summary>
    /// Method used to raise the CanExecuteChanged event
    /// to indicate that the return value of the CanExecute
    /// method has changed.
    /// </summary>
    public void RaiseCanExecuteChanged()
    {
        var handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

И, наконец, вы можете получить это в вашей команде:

private RelayCommand btnclickcommmand;

    public RelayCommand MyBtnClickCommand
    {
        get { return btnclickcommmand; }
        set { btnclickcommmand = value; }
    }

 btnclickcommmand = new RelayCommand(() =>
        {
            //TODO            
            mytag = btnclickcommmand.BtnTag;
            System.Diagnostics.Debug.WriteLine(mytag+"Button create the flyout");
        });      
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...