How to set the background using acrylic brush through C# in UWP? - c#

I've tried the following:
{
ContentDialog dialog = new ContentDialog()
{
Title = title,
Content = text,
CloseButtonText = closeButtonText
};
dialog.Background = new AcrylicBrush()
{
BackgroundSource = 0,
TintOpacity = 0.5,
Opacity = 0.5,
};
await dialog.ShowAsync();
}
P.S. - Sorry for the Russian and my bad English. Thank you in advance đź‘Ť

Your code is well if you can see the button after the content dialog.
The code that I do not use acrylic brush.
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
var title = "title";
var text = "text";
var closeButtonText = "close";
ContentDialog dialog = new ContentDialog()
{
Title = title,
Content = text,
CloseButtonText = closeButtonText
};
dialog.Background = new SolidColorBrush(Color.FromArgb(255, 202, 24, 37));
await dialog.ShowAsync();
}
The code that I use acrylic brush.
private async void Button_OnClick(object sender, RoutedEventArgs e)
{
var title = "title";
var text = "text";
var closeButtonText = "close";
ContentDialog dialog = new ContentDialog()
{
Title = title,
Content = text,
CloseButtonText = closeButtonText
};
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent(
"Windows.UI.Xaml.Media.XamlCompositionBrushBase"))
{
// check that this API is available on the user’s machine
dialog.Background = new AcrylicBrush()
{
BackgroundSource = Windows.UI.Xaml.Media.AcrylicBackgroundSource.HostBackdrop,
TintOpacity = 0.5,
FallbackColor = Color.FromArgb(255, 202, 24, 37),
Opacity = 0.5,
};
}
await dialog.ShowAsync();
}
See Acrylic material - Windows UWP applications
Customize Acrylic Brush in UWP Applications

Related

Set Back Button Title on Xamarin Forms C#

im quite new to c# and Xamarin and I've just encountered a problem. I can't seem to be able to set the back button title on a navigation page. Ive tried using the static SetBackButtonTitle method but it does not seem to set the back button to the title I want which is
'Test' but instead its giving me the 'default' title which is "Back".
// The root page of your application
var content = new ContentPage();
var CompanyName = new Label();
CompanyName.HorizontalTextAlignment = TextAlignment.Center;
CompanyName.Text = "Test";
var NextPage = new Button();
NextPage.Text = "Next Page";
NextPage.Font = Font.SystemFontOfSize(NamedSize.Large);
NextPage.BorderWidth = 1;
NextPage.HorizontalOptions = LayoutOptions.Center;
NextPage.VerticalOptions = LayoutOptions.CenterAndExpand;
var layout = new StackLayout();
layout.VerticalOptions = LayoutOptions.CenterAndExpand;
layout.Children.Add(CompanyName);
layout.Children.Add(NextPage);
content.Content = layout;
var content2 = new ContentPage();
var navigation = new NavigationPage(content);
NavigationPage.SetHasBackButton(navigation,true);
NavigationPage.SetBackButtonTitle(navigation,"Test");
NextPage.Clicked += NextPageClicked;
async void NextPageClicked(object sender, EventArgs e)
{
await navigation.PushAsync(content2);
}
MainPage = navigation;
}
If you want to change the back button's title(at the left in the navigation bar) in the second page, you should call the method SetBackButtonTitle with first page as parameter. So please modify NavigationPage.SetBackButtonTitle(navigation,"Test"); to NavigationPage.SetBackButtonTitle(content,"Test");
For those who use Xamarin.Forms WPF if you want to change back button title you can do this:
protected override void OnDisappearing()
{
base.OnDisappearing();
Title = "";
}
protected override void OnAppearing()
{
base.OnAppearing();
Title = "MyTitle";
}

Dynamically added controls are not visible in UWP C#

I'm trying to create a download manager for UWP in C#. I need to add ProgressBar for download progress, TextBlock for showing download status and another TextBox for displaying download file name. My code works fine when I compile only download manager's code separately (on a new uwp app). It shows progress properly in runtime.
My codes are-
private async void Downloadbtn_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Uri url = new Uri(urlBox.Text);
string fileName = ResolveName(urlBox.Text);
FolderPicker folderPicker = new FolderPicker();
folderPicker.ViewMode = PickerViewMode.List;
folderPicker.FileTypeFilter.Add("*.*");
StorageFolder downloadfolder = await folderPicker.PickSingleFolderAsync();
if (folderPicker != null)
{
StorageFile downloadFile = await downloadfolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
operation = downloader.CreateDownload(url, downloadFile);
try
{
TextBlock fileNameText = new TextBlock();
fileNameText.Text = fileName;
ProgressBar ProgressIndicator = new ProgressBar();
ProgressIndicator.Name = "progress";
TextBlock progressText = new TextBlock();
progressText.Name = "progressText";
StackPanel panel = new StackPanel();
panel.Children.Add(fileNameText);
panel.Children.Add(ProgressIndicator);
panel.Children.Add(progressText);
MainStack.Children.Add(panel);
cts = new CancellationTokenSource();
Progress<DownloadOperation> progressCallBack = new Progress<DownloadOperation>(Progress);
await operation.StartAsync().AsTask(cts.Token,progressCallBack);
}
catch (Exception)
{
await operation.ResultFile.DeleteAsync();
operation = null;
}
}
}
private string ResolveName(string fileName)
{
if (fileName.Contains("/"))
{
int last = fileName.LastIndexOf("/");
fileName = fileName.Substring(last + 1, fileName.Length - last - 1);
}
if (fileName.Contains("%20"))
{
fileName = fileName.Replace("%20", " ");
}
return fileName;
}
private void Progress(DownloadOperation operation)
{
ProgressBar c = new ProgressBar();
c = (ProgressBar)(MainStack.FindName("progress" ));
TextBlock c1 = new TextBlock();
c1 = (TextBlock)(MainStack.FindName("progressText"));
double received = operation.Progress.BytesReceived;
double toReceive = operation.Progress.TotalBytesToReceive;
double progress = received * 100 / toReceive;
((ProgressBar)c).Value = progress;
c1.Text = received + "KB received of " + toReceive + "KB";
if (received == toReceive)
c1.Text = "Download Completed";
}
MainStack is the stackpanel where new download and its ui elements are added.
But UI elements (progressbar, textblock) are not visible when I'm putting above codes in a different app like-
private async void GetDownloadData(Uri uri)
{
string fileName = ResolveName(uri.tostring());
FolderPicker folderPicker = new FolderPicker();
folderPicker.ViewMode = PickerViewMode.List;
folderPicker.FileTypeFilter.Add("*.*");
StorageFolder downloadfolder = await folderPicker.PickSingleFolderAsync();
if (folderPicker != null)
{
StorageFile downloadFile = await downloadfolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
operation = downloader.CreateDownload(url, downloadFile);
try
{
TextBlock fileNameText = new TextBlock();
fileNameText.Text = fileName;
ProgressBar ProgressIndicator = new ProgressBar();
ProgressIndicator.Name = "progress" ;
TextBlock progressText = new TextBlock();
progressText.Name = "progressText";
StackPanel panel = new StackPanel();
panel.Children.Add(fileNameText);
panel.Children.Add(ProgressIndicator);
panel.Children.Add(progressText);
MainStack.Children.Add(panel);
cts = new CancellationTokenSource();
Progress<DownloadOperation> progressCallBack = new Progress<DownloadOperation>(Progress);
await operation.StartAsync().AsTask(cts.Token,progressCallBack);
}
catch (Exception)
{
await operation.ResultFile.DeleteAsync();
operation = null;
}
}
}
In the second code, I'm calling GetDownloadData(uri) method to initiate download rather than calling it upon button click event. And also this method is placed in different XAML page (other than main page).
The only problem with the second code is that, no progressbar or textblock is added at run time in MainStack (stackpanel). I tried solving this problem by replacing stackpanel with listview and listbox but problem doesn't resolve.
Any idea, what am I missing here.

Capture entry value in click event

I have a entry control added using c# to my xamarin.forms app. I also have a toolbaritem, on click of which I would like to save the data which is being entered by user.
I cannot access the text value in click event, I get this error:
Error 20 The name 'txtTest' does not exist in the current context
Here is my code sample:
public SettingsPage()
{
ToolbarItem Settings = new ToolbarItem();
Settings.Name = "Settings";
Settings.Clicked += OnClick_Settings;
Settings.Order = ToolbarItemOrder.Primaru;
ToolbarItems.Add(Settings);
loadData();
}
async public void loadData()
{
Label lblTest = new Label { Text = "Test", FontAttributes = FontAttributes.Bold };
Entry txtTest = new Entry();
StackLayout stLTest = new StackLayout
{
Padding = new Thickness(10, 0, 0, 0),
Children ={
lblTest,
txtTest
}
};
Content = stTest
}
async private void OnClick_Settings(object sender, EventArgs e)
{
var test= txtTest.Text;
}
In my OnClick_Settings, I cannot find text value.
you have txtTest in loadData() method.
you should move it out of there.
Do this
Entry txtTest;
async public void loadData()
{
Label lblTest = new Label { Text = "Test", FontAttributes = FontAttributes.Bold };
txtTest = new Entry();
StackLayout stLTest = new StackLayout
{
Padding = new Thickness(10, 0, 0, 0),
Children ={
lblTest,
txtTest
}
};
Content = stTest
}

Showing CustomDialog as modal dialog and get result (mahapps)

I have a class which creates SimpleDialog (now CustomDialog) with custom contents. So far I'm successful in showing it & closing it. But how to return its return to parent window? Just like how ShowDialog method does? The code so far is,
internal void fnShowDialog(MainWindow parent)
{
SimpleDialog dialog = new SimpleDialog();
StackPanel panel = new StackPanel();
Label block = new Label() { Content = "custom message" };
TextBlock block1 = new TextBlock() { Text = "custom message", FontSize = 22 };
Button button = new Button() { Content = "close" };
button.Click += (s, e) =>
{
parent.HideMetroDialogAsync((BaseMetroDialog)dialog);
};
panel.Children.Add(block);
panel.Children.Add(block1);
panel.Children.Add(button);
dialog.DialogBody = panel;
parent.ShowMetroDialogAsync((BaseMetroDialog)dialog);
}
I need to know the result of this dialog for further precessing accordingly.
I suggest you get the dialog's result in the Click event handler, the same place you call HideMetroDialogAsync.
Every Form has DialogResult property. You can set them on some event and then check the enum value of them in your dialog objects after closing the Form.
BaseMetroDialog could have DialogResult property which would be visible to parent.
This is a simple asynchronous process:
You should use await keyword to get the result:
var result = await parent.ShowMetroDialogAsync((BaseMetroDialog)dialog);
Don't forget to return result; at the end of the method.
Change your method definition to return this result like this:
internal async Task<MessageDialogResult> fnShowDialog(MainWindow parent)
This is the full method:
internal async Task<MessageDialogResult> fnShowDialog(MainWindow parent)
{
SimpleDialog dialog = new SimpleDialog();
StackPanel panel = new StackPanel();
Label block = new Label() { Content = "custom message" };
TextBlock block1 = new TextBlock() { Text = "custom message", FontSize = 22 };
Button button = new Button() { Content = "close" };
button.Click += (s, e) =>
{
parent.HideMetroDialogAsync((BaseMetroDialog)dialog);
};
panel.Children.Add(block);
panel.Children.Add(block1);
panel.Children.Add(button);
dialog.DialogBody = panel;
var result = await parent.ShowMetroDialogAsync((BaseMetroDialog)dialog);
return result;
}
You can use this method with an await like this:
var result = awiat fnShowDialog(parent);
if(result == ...)
{...}

How to show toast after performing some functionality in windows phone 8

I want to show something like toast after some functionality performed. i-e I have a save button and I want that when it pressed then a toast should be shown with the text Record Saved etc. I read posts that show toasts are only for back-ground agents. I know someone will give me good guidance. please specify some code.
Thanks
You can use the Toast Prompt from the Coding4Fun Toolkit to perform a toast notification via code. After referencing the toolkit (ideally via NuGet) you can use it like this:
ToastPrompt toast = new ToastPrompt();
toast.Title = "Your app title";
toast.Message = "Record saved.";
toast.TextOrientation = Orientation.Horizontal;
toast.MillisecondsUntilHidden = 2000;
toast.ImageSource = new BitmapImage(new Uri("ApplicationIcon.png", UriKind.RelativeOrAbsolute));
toast.Show();
I prefer ProgressIndicator in my apps but you can use Popup or ToastPrompt.
Sample project.
// popup member
private Popup popup;
// creates popup
private Popup CreatePopup()
{
// text
TextBlock tb = new TextBlock();
tb.Foreground = (Brush)this.Resources["PhoneForegroundBrush"];
tb.FontSize = (double)this.Resources["PhoneFontSizeMedium"];
tb.Margin = new Thickness(24, 32, 24, 12);
tb.Text = "Custom toast message";
// grid wrapper
Grid grid = new Grid();
grid.Background = (Brush)this.Resources["PhoneAccentBrush"];
grid.Children.Add(tb);
grid.Width = this.ActualWidth;
// popup
Popup popup = new Popup();
popup.Child = grid;
return popup;
}
// hides popup
private void HidePopup()
{
SystemTray.BackgroundColor = (Color)this.Resources["PhoneBackgroundColor"];
this.popup.IsOpen = false;
}
// shows popup
private void ShowPopup()
{
SystemTray.BackgroundColor = (Color)this.Resources["PhoneAccentColor"];
if (this.popup == null)
{
this.popup = this.CreatePopup();
}
this.popup.IsOpen = true;
}
// shows and hides popup with a delay
private async void ButtonClick(object sender, RoutedEventArgs e)
{
this.ShowPopup();
await Task.Delay(2000);
this.HidePopup();
}
using Windows.UI.Notifications;
var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
var txtNodes = toastXmlContent.GetElementsByTagName("text");
txtNodes[0].AppendChild(toastXmlContent.CreateTextNode("First Line"));
txtNodes[1].AppendChild(toastXmlContent.CreateTextNode("Second Line" ));
var toast = new ToastNotification(toastXmlContent);
var toastNotifier = ToastNotificationManager.CreateToastNotifier();
toastNotifier.Show(toast);

Categories