Change Visual State Pressed Button Background UWP - c#

I know how to do this in XAML, but I want to change the colors in a ContentDialog.
I can change the background and forground color, but I would also like to change the button colors when in a specific state ("Pressed", "PointOver", ...).
var contentDialog = new ContentDialog
{
Content = "Test",
Title = "Test",
PrimaryButtonText = "OK"
};
var buttonStyle = new Style(typeof(Button));
buttonStyle.Setters.Add(new Setter(Control.BackgroundProperty, Colors.Yellow));
buttonStyle.Setters.Add(new Setter(Control.ForegroundProperty, Colors.White));
buttonStyle.Setters.Add(new Setter(Windows.UI.Xaml.Controls.Primitives.ButtonBase.IsPressedProperty, Colors.Green));
buttonStyle.Setters.Add(new Setter(VisualState...))
contentDialog.PrimaryButtonStyle = buttonStyle;
await contentDialog.ShowAsync();
How can I do this in code?

Override the ButtonBackgroundPressed theme resource:
contentDialog.Resources["ButtonBackgroundPressed"] = new SolidColorBrush(Colors.Red);
Or define a completely custom ControlTemplate:
const string Xaml = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TargetType=\"Button\">" +
"...</ControlTemplate>";
var buttonStyle = new Style(typeof(Button));
buttonStyle.Setters.Add(new Setter(Control.TemplateProperty, XamlReader.Load(Xaml) as ControlTemplate));
contentDialog.PrimaryButtonStyle = buttonStyle;

Related

C# Changing color on label doesnt work in my stacklayout

i am using code behind visual state managers to give selected labels a background color, but this doesnt work, any idea why?
var frameStackLayoutX = new StackLayout
{
Spacing = 5
};
var vsg = new VisualStateGroup() { Name = "CommonStates" };
var vs = new VisualState { Name = "Selected" };
vs.Setters.Add(new Setter
{
TargetName = "Selected",
Property = Label.BackgroundColorProperty,
Value = Colors.Red
});
vsg.States.Add(vs);
VisualStateManager.GetVisualStateGroups(frameStackLayoutX).Add(vsg);
var LabelName = new Label();
LabelName.Text = "Jhon Doe"
LabelName .WidthRequest = 100;
LabelName .Padding = new Thickness(10, 0, 0, 0);
frameStackLayoutX.Add(LabelName );
return frameStackLayoutX;
This is inside a grid, wherei use _lines.SelectedItem = pressedItem; to make sure that I can click on my label.

how to add styles for content dialog title and button using c# for UWP app

ContentDialog Dialog = new ContentDialog();
private async void DisplaySessionDialog()
{
var bStyle = new Style(typeof(Button));
bStyle.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush(Colors.White)));
bStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Colors.Maroon)));
bStyle.Setters.Add(new Setter(Button.HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
bStyle.Setters.Add(new Setter(Button.VerticalContentAlignmentProperty, VerticalAlignment.Center));
bStyle.Setters.Add(new Setter(Button.CornerRadiusProperty, new CornerRadius(15)));
bStyle.Setters.Add(new Setter(Button.PaddingProperty, new Thickness(5)));
bStyle.Setters.Add(new Setter(Button.MarginProperty, HorizontalAlignment.Center));
bStyle.Setters.Add(new Setter(Button.FontSizeProperty, 18));
Dialog.Title = val.SessionExpireTitle;
Dialog.Content = val.SessionExpireContent;
Dialog.PrimaryButtonText = val.SessionExpireButtonLabel;
Dialog.PrimaryButtonStyle = bStyle;
Dialog.FontSize = 18;
await Dialog.ShowAsync();
}
The above code is working fine. However, I want to alignment button as a centre and title alignment centre, content also from left. I tried more ways and search a lot of things I did not find any solutions . Please help me, is there any way to align title in c# for UWP app

How do I Inherit a WPF DataGrid Cell Style when programmatically adding a DataTrigger?

I'm writing a WPF application which makes use of the DataGrid control. I'm using the MaterialDesign theme to style the application and this gives a nice look and feel.
However for complex reasons I wont go into here I'm required to add the columns into the dataGrid programmatically. For some of the columns I'm also styling the columns to highlight pass / fail in red. When I do this I loose 'some of the styling' provided by material design for that columns. Namely the Horizontal and Vertical alignment.
The code to the above is as follows:
// Define Setter
Setter setterResultFail = new Setter();
setterResultFail.Property = DataGridCell.BackgroundProperty;
setterResultFail.Value = Brushes.Red;
// Create a column for the Site.
var currentColumn = new DataGridTextColumn();
currentColumn.Header = "Device #";
currentColumn.Binding = new Binding("Device");
ResultsDataGrid.Columns.Add(currentColumn);
// Create a column for the Site.
currentColumn = new DataGridTextColumn();
currentColumn.Header = "Site";
currentColumn.Binding = new Binding("Site");
ResultsDataGrid.Columns.Add(currentColumn);
// Create a column for the Pass Fail.
currentColumn = new DataGridTextColumn();
currentColumn.Header = "Pass Fail";
currentColumn.Binding = new Binding("PassFail") { Converter = new BooleanToPassFailConverter() };
// Create cellstyle to make the cell 'red' when the PassFail value is False. ( this is done via a data trigger )
cellStyle = new Style(typeof(DataGridCell));
// Define First DataTrigger that sets a CELL red if the value is a fail.
dataTrigger = new DataTrigger();
dataTrigger.Value = "False";
dataTrigger.Binding = new Binding("PassFail");
dataTrigger.Setters.Add(setterResultFail);
// Add the data-triggers to the cell style.
cellStyle.Triggers.Clear();
cellStyle.Triggers.Add(dataTrigger);
// Apply the newly created cell style.
currentColumn.CellStyle = cellStyle;
ResultsDataGrid.Columns.Add(currentColumn);
Clearly the new cellStyle is used instead of the MaterialDesign style. I've tried setting the values for vertical / horizontal manually but I can't get it to look correct:
Setter setterTextContentHorizonalAlignment = new Setter();
setterTextContentHorizonalAlignment.Property = DataGridCell.HorizontalContentAlignmentProperty;
setterTextContentHorizonalAlignment.Value = HorizontalAlignment.Center;
Setter setterTextContentVerticalAlignment = new Setter();
setterTextContentVerticalAlignment.Property = DataGridCell.VerticalContentAlignmentProperty;
setterTextContentVerticalAlignment.Value = VerticalAlignment.Center;
Setter setterTextHorizontalAlignment = new Setter();
setterTextHorizontalAlignment.Property = DataGridCell.HorizontalAlignmentProperty;
setterTextHorizontalAlignment.Value = HorizontalAlignment.Center;
Setter setterTextVerticalAlignment = new Setter();
setterTextVerticalAlignment.Property = DataGridCell.VerticalAlignmentProperty;
setterTextVerticalAlignment.Value = VerticalAlignment.Center;
cellStyle.Setters.Add(setterTextContentHorizonalAlignment);
cellStyle.Setters.Add(setterTextContentVerticalAlignment);
cellStyle.Setters.Add(setterTextHorizontalAlignment);
cellStyle.Setters.Add(setterTextVerticalAlignment);
Is there a way I can add to the style rather than replace it...similar to the BasedOn approch in XAML?
After much wasting of time on this question I came across Danny Beckett's similar question and King King's answer. By using his answer and applying it to the specific cell I was having trouble with it fixed the issue:King King's answer
// Create a column for the Pass Fail.
currentColumn = new DataGridTextColumn();
currentColumn.Header = "Pass Fail";
currentColumn.Binding = new Binding("PassFail") { Converter = new BooleanToPassFailConverter() };
// Create cellstyle to make the cell 'red' when the PassFail value is False. ( this is done via a data trigger )
cellStyle = new Style(typeof(DataGridCell));
// Define First DataTrigger that sets a CELL red if the value is a fail.
dataTrigger = new DataTrigger();
dataTrigger.Value = "False";
dataTrigger.Binding = new Binding("PassFail");
dataTrigger.Setters.Add(setterResultFail);
// Add the data-triggers to the cell style.
cellStyle.Triggers.Clear();
cellStyle.Triggers.Add(dataTrigger);
//root visual of the ControlTemplate for DataGridCell is a Border
var border = new FrameworkElementFactory(typeof(Border));
border.SetBinding(Border.BorderBrushProperty, new Binding("BorderBrush")
{
RelativeSource = RelativeSource.TemplatedParent
});
border.SetBinding(Border.BackgroundProperty, new Binding("Background") { RelativeSource = RelativeSource.TemplatedParent });
border.SetBinding(Border.BorderThicknessProperty, new Binding("BorderThickness") { RelativeSource = RelativeSource.TemplatedParent });
border.SetValue(SnapsToDevicePixelsProperty, true);
//the only child visual of the border is the ContentPresenter
var contentPresenter = new FrameworkElementFactory(typeof(ContentPresenter));
contentPresenter.SetBinding(SnapsToDevicePixelsProperty, new Binding("SnapsToDevicePixelsProperty") { RelativeSource = RelativeSource.TemplatedParent });
contentPresenter.SetBinding(VerticalAlignmentProperty, new Binding("VerticalContentAlignment") { RelativeSource = RelativeSource.TemplatedParent });
contentPresenter.SetBinding(HorizontalAlignmentProperty, new Binding("HorizontalContentAlignment") { RelativeSource = RelativeSource.TemplatedParent });
//add the child visual to the root visual
border.AppendChild(contentPresenter);
//here is the instance of ControlTemplate for DataGridCell
var template = new ControlTemplate(typeof(DataGridCell));
template.VisualTree = border;
//define the style
cellStyle.Setters.Add(new Setter(TemplateProperty, template));
cellStyle.Setters.Add(new Setter(VerticalContentAlignmentProperty, VerticalAlignment.Center));
cellStyle.Setters.Add(new Setter(HorizontalContentAlignmentProperty, HorizontalAlignment.Center));
// Apply the newly created cell style.
currentColumn.CellStyle = cellStyle;

Retreive stackpanel children from GridViewItem (UWP)

I'm wondering how I can get the contents of a stackpanel which has been added to a GridViewItem (YouTube data API, the stackpanel contains a bitmap image for a thumbnail, the title of the video and a hidden TextBlock with the video ID for reference).
To clarify, I need to be able to obtain the contents of the StackPanel that is contained in the GridViewItem (such as the string of that hidden TextBox) so I can use the data to display the correct video.
Here's the code I use to create the stackpanel.
public async Task SearchByKeyword(string searchTerm)
{
GeneralFunctions gf = new GeneralFunctions();
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = gf.YouTubeAPIKey,
ApplicationName = this.GetType().ToString()
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = searchTerm; // Replace with your search term.
searchListRequest.MaxResults = 50;
searchListRequest.SafeSearch = SearchResource.ListRequest.SafeSearchEnum.Strict;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = await searchListRequest.ExecuteAsync();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
// Add each result to the appropriate list, and then display the lists of
// matching videos, channels, and playlists.
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
// Create a new StackPanel to insert as a ListViewItem
StackPanel sPanel = new StackPanel();
sPanel.HorizontalAlignment = HorizontalAlignment.Stretch;
sPanel.VerticalAlignment = VerticalAlignment.Stretch;
sPanel.Orientation = Orientation.Vertical;
sPanel.Width = 160;
sPanel.Height = 160;
// Create new StackPanel "Child" elements with alignment and width
TextBlock tb1 = new TextBlock();
tb1.Text = searchResult.Snippet.Title;
tb1.TextWrapping = TextWrapping.WrapWholeWords;
tb1.Width = 160;
// Create new StackPanel "Child" elements with alignment and width
TextBlock tb2 = new TextBlock();
tb2.Text = searchResult.Snippet.ChannelId;
tb2.TextWrapping = TextWrapping.WrapWholeWords;
tb2.Width = 160;
// Create new StackPanel child element for a 120x120 thumbnail of the videos from the search results
Image image = new Image();
image.Source = new BitmapImage(new Uri(searchResult.Snippet.Thumbnails.Default__.Url, UriKind.Absolute));
// Add a "hidden" child element to each stackpanel to hold the video identity
TextBlock h1 = new TextBlock();
h1.Text = searchResult.Id.VideoId.ToString();
h1.Visibility = Visibility.Collapsed;
h1.TextWrapping = TextWrapping.WrapWholeWords;
sPanel.Children.Add(image);
sPanel.Children.Add(tb1);
sPanel.Children.Add(tb2);
sPanel.Children.Add(h1);
SearchResults.Items.Add(sPanel);
break;
case "youtube#channel":
//SearchResults.Items.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
//playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
//Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
//Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
//Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
}
Any help is appreciated.
Thanks
I guess I should never code tired right? The answer to my own question is actually very very simple
if (SearchResults.SelectedItems.Count > 0)
{
StackPanel sp = (StackPanel)SearchResults.SelectedItem;
TextBlock tb1 = (TextBlock)sp.Children[1];
TextBlock tb2 = (TextBlock)sp.Children[2];
TextBlock hf1 = (TextBlock)sp.Children[3];
}

about wrap text in ContentDialogResult in winphone 8.1 RT

I have long string and show it in ContentDialogResult as
var dlg = new ContentDialog()
{
Title = sTitle,
Content = "This is very long string and i want wrap it but it only appear in 1 line on content of ContentDialogResult. Please help me!",
PrimaryButtonText = sTextBtnMain,
SecondaryButtonText = sTextBtnSub
};
but it only show on 1 line and no wrap. How i can wrap it without custom xaml for ContentDialogResult.
Thanks for all support!
ContentDialog accepts any object as Title and Content property. So, create TextBlock, add TextWrapping property and pass it to Content instead of string object. It will work.
TextBlock txtBlock = new TextBlock();
txtBlock.Text = "This is very long string and i want wrap it but it only appear in 1 line on content of ContentDialogResult. Please help me!";
txtBlock.TextWrapping = TextWrapping.Wrap;
ContentDialog dialog = new ContentDialog()
{
Title = sTitle,
Content = txtBlock,
PrimaryButtonText = sTextBtnMain,
SecondaryButtonText = sTextBtnSub
};

Categories

Resources