Как передать строку из класса данных в ContentDialog - PullRequest
0 голосов
/ 14 июля 2020

Как я могу передать строковое значение из моего класса данных в диалоговое окно содержимого при нажатии кнопки в моем основном представлении списка? Есть ли способ сделать это без использования свойств зависимостей в этом случае или нужно использовать что-то еще?

Ожидаемый результат

enter image description here

enter image description here

Current app layout

image

Класс элемента (электронная почта)

public class Email
{
    public string From { get; set; }
    public string Body { get; set; }
    public bool ShowButton { get; set; }
    public string DialogTitle { get; set; }
    public string DialogContent { get; set; }
}

public class MyEmailManager
{
    public static List<Email> GetEmails()
    {
        var MyEmails = new List<Email>
        {
            new Email
            {
                From = "Steve Johnson",
                Body = "Are you available for lunch tomorrow? A client would like to discuss a project with you.",
                ShowButton = true,
                DialogTitle = "Title A",
                DialogContent = "Content A"
            },
            new Email
            {
                From = "Pete Davidson",
                Body = "Don't forget the kids have their soccer game this Friday. We have to supply end of game snacks.",
                ShowButton = false,
                DialogTitle = "",
                DialogContent = ""
            },
            new Email
            {
                From = "OneDrive",
                Body = "Your new album.\r\nYou uploaded some photos to your OneDrive and automatically created an album for you.",
                ShowButton = false,
                DialogTitle = "",
                DialogContent = ""
            },
            new Email
            {
                From = "Twitter",
                Body = "Here are some people we think you might like to follow:\r\n.@randomPerson\r\nAPersonYouMightKnow",
                ShowButton = true,
                DialogTitle = "Title D",
                DialogContent = "Content D"
            }
        };

        return MyEmails;
    }
}

Класс страницы

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();

            Binding myBinding = new Binding()
            {
                Source = Emails,
                Mode = BindingMode.OneWay
            };

            MyMasterDetailsView.SetBinding(MasterDetailsView.ItemsSourceProperty, myBinding);

            var emails = MyEmailManager.GetEmails();
            emails.ForEach(email => Emails.Add(email));
        }

        public ObservableCollection<Email> Emails = new ObservableCollection<Email>();

        private async void BtnMoreMasterItem_Click(object sender, RoutedEventArgs e)
        {
            ContentDialog MyDialog = new ContentDialog
            {
                Title = Emails.DialogTitle,
                Content = Emails.DialogContent,
                CloseButtonText = "OK"
            };

            ContentDialogResult result = await MyDialog.ShowAsync();
        }
    }

1 Ответ

0 голосов
/ 15 июля 2020

Как передать строку из класса данных в ContentDialog

В этом сценарии вы можете привязать свойство MoreButton Command и передать текущее DataContext в качестве параметра метода с CommandParameter.

Например.

public MainPage()
{
    this.InitializeComponent();
    this.DataContext = this;
    Emails = MyEmailManager.GetEmails();
}

public ICommand OpenDialog
{
    get
    {
        return new CommadEventHandler<Email>((s) => OpenDialogCommandFun(s));
    }
}
private async void OpenDialogCommandFun(Email s)
{
    ContentDialog dialogServiceUpdates = new ContentDialog
    {
        Title = s.From,
        Content = s.Body,
        CloseButtonText = "OK"
    };

    ContentDialogResult result = await dialogServiceUpdates.ShowAsync();
}

Xaml

<Button
    x:Name="MoreBtn"
    Grid.Column="1"
    Margin="10"
    Padding="10"
    HorizontalAlignment="Right"
    VerticalAlignment="Top"
    Background="Transparent" 
    Command="{Binding ElementName=RootGrid, Path=DataContext.OpenDialog}"
    CommandParameter="{Binding}"
    Content="&#xE712;"
    FontFamily="Segoe MDL2 Assets"
    Visibility="{Binding ShowButton, Converter={StaticResource MyConveter}}"
    />

Для лучшего понимания я загрузил пример кода здесь , проверьте его.

...