I want to add or remove a few controls to a StackPanel when a certain radio button is checked.
I suspect setting the foreground binding of the Slider control is wrong.
MainWindow.xaml
<StackPanel Name ="Upgrades" VerticalAlignment="Center" HorizontalAlignment="Center">
<RadioButton Name="rb1" Content="Upgrade rb1" />
<RadioButton Name="rb2" Content="Upgrade rb2" />
<RadioButton Name="rb3" Content="Upgrade rb3" />
<RadioButton Name="rb4" Content="Upgrade rb4" IsChecked="True"/>
<RadioButton Name="AllFour" Content="All Four" Checked="AllFour_Checked" Unchecked="AllFour_Unchecked" />
<Button Name="StartUpgrades" Margin="0 0 0 0" Click="StartUpgrades_Click" >Start</Button>
</StackPanel>
<!-- I want to add these controls to the stackpanel before the StartUpgrades Button Control
<Label Name="SelectThreads" HorizontalAlignment="Center">Select Threads</Label>
<Slider Name="SliderThreadAmount" Minimum="1" Maximum="4" TickFrequency="1" IsSnapToTickEnabled="True" Style="{DynamicResource SliderStyle}" Foreground="{DynamicResource SliderSelectionRangeBackgroundBrush}" IsVisibleChanged="SliderThreadAmount_IsVisibleChanged"></Slider>
<Label HorizontalAlignment="Center" Name="SliderThreadValue" BorderBrush="Gray" Content="{Binding ElementName=SliderThreadAmount,Path=Value}"></Label> -->
MainWindow.xaml.cs
private void AllFour_Unchecked(object sender, RoutedEventArgs e)
{
Label label1 = new Label();
label1.HorizontalAlignment = HorizontalAlignment.Center;
Slider sl = new Slider();
sl.Minimum = 1;
sl.Maximum = 4;
sl.TickFrequency = 1;
sl.IsSnapToTickEnabled = true;
sl.SetResourceReference(Control.StyleProperty, "SliderStyle");
sl.Foreground.SetValue(Control.StyleProperty, "SliderSelectionRangeBackgroundBrush");
Label label2 = new Label();
label2.HorizontalAlignment = HorizontalAlignment.Center;
label2.BorderBrush = new SolidColorBrush(Colors.Gray);
label2.Content = "{Binding ElementName=sl,Path=Value}";
Upgrades.Children.Add(label1);
Upgrades.Children.Add(sl);
Upgrades.Children.Add(label2);
}
private void AllFour_Checked(object sender, RoutedEventArgs e)
{
Upgrades.Children.Remove(label1);
Upgrades.Children.Remove(sl);
Upgrades.Children.Remove(label2);
}
To dynamically add the radio buttons you can use an ItemsControl bound to a collection
<StackPanel Name ="Upgrades" VerticalAlignment="Center" HorizontalAlignment="Center">
<ItemsControl ItemsSource="{Binding UpgradeButtons}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding UpgradeName}" IsChecked="{Binding UpgradeChecked}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<RadioButton Name="AllFour" Content="All Four" IsChecked="{Binding AllFourSelected}" />
<Button Name="StartUpgrades" Margin="0 0 0 0" Command="{Binding StartUpgrades}" />
</StackPanel>
This does assume moving towards a MVVM style, with a MainViewModel and each upgrade would be a UpgradeViewModel.
Try this to set the Foreground property of the Slider:
sl.SetResourceReference(Slider.ForegroundProperty, "SliderSelectionRangeBackgroundBrush");
And this to bind the Content property of the Label to the Value property of the Slider:
label2.SetBinding(Label.ContentProperty, new Binding("Value") { Source = sl });
I get this message: An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationCore.dll
Use the dispatcher to remove add the controls. Here is a full example that works:
Slider sl;
Label label1;
Label label2;
private void AllFour_Unchecked(object sender, RoutedEventArgs e)
{
label1 = new Label();
label1.HorizontalAlignment = HorizontalAlignment.Center;
sl = new Slider();
sl.Minimum = 1;
sl.Maximum = 4;
sl.TickFrequency = 1;
sl.IsSnapToTickEnabled = true;
sl.SetResourceReference(Control.StyleProperty, "SliderStyle");
sl.SetResourceReference(Slider.ForegroundProperty, "SliderSelectionRangeBackgroundBrush");
label2 = new Label();
label2.HorizontalAlignment = HorizontalAlignment.Center;
label2.BorderBrush = new SolidColorBrush(Colors.Gray);
label2.SetBinding(Label.ContentProperty, new Binding("Value") { Source = sl });
Dispatcher.BeginInvoke(new Action(() =>
{
Upgrades.Children.Add(label1);
Upgrades.Children.Add(sl);
Upgrades.Children.Add(label2);
}), System.Windows.Threading.DispatcherPriority.Background);
}
private void AllFour_Checked(object sender, RoutedEventArgs e)
{
Upgrades.Children.Remove(label1);
Upgrades.Children.Remove(sl);
Upgrades.Children.Remove(label2);
}
Related
On my application I am able to dynamically create Radio Buttons and I need to have the ability to add a right click to each dynamically created button.
For an example button I added the below code would have the right click as needed.
XAML:
<RadioButton Content="3001" x:Name="myButton" Width="75" Height="40" FontSize="25" ContextRequested="MyButton_ContextRequested"/>
C# Code Behind:
private void ShowMenu(bool isTransient)
{
FlyoutShowOptions myOption = new FlyoutShowOptions();
myOption.ShowMode = isTransient ? FlyoutShowMode.Transient : FlyoutShowMode.Standard;
CommandBarFlyout1.ShowAt(myButton, myOption);
}
private void MyButton_ContextRequested(Windows.UI.Xaml.UIElement sender, ContextRequestedEventArgs args)
{
// always show a context menu in standard mode
ShowMenu(true);
}
Dynamic Button Add -
XAML:
<StackPanel x:Name="SiteAddPanel" Orientation="Horizontal" VerticalAlignment="Top">
<Button PointerEntered="Button_PointerEntered" PointerExited="Button_PointerExited" Width="80" Height="45">
<muxc:AnimatedIcon x:Name="SearchAnimatedIcon">
<muxc:AnimatedIcon.Source>
<animatedvisuals:AnimatedFindVisualSource/>
</muxc:AnimatedIcon.Source>
</muxc:AnimatedIcon>
<Button.Flyout>
<Flyout
x:Name="flyoutSiteID">
<StackPanel Orientation="Horizontal">
<TextBox
x:Name="seachSiteID"
Header="Enter the 4 Digit Site Number"
PlaceholderText="SiteID"
>
<TextBox.KeyboardAccelerators>
<KeyboardAccelerator Key="Enter" Invoked="KeyboardAccelerator_Invoked"/>
</TextBox.KeyboardAccelerators>
</TextBox>
<Button VerticalAlignment="Bottom" Click="Add_Site">
<SymbolIcon Symbol="Add">
</SymbolIcon>
<!--<Button.KeyboardAccelerators>
<KeyboardAccelerator Key="Enter"/>
</Button.KeyboardAccelerators>-->
</Button>
</StackPanel>
</Flyout>
</Button.Flyout>
</Button>
<AppBarSeparator Width="20"/>
</StackPanel>
C# Code Behind:
private void Add_Site(object sender, RoutedEventArgs e)
{
var btnName = "btnSite" + seachSiteID.Text;
if (SiteAddPanel.Children.Count <= 6)
{
RadioButton button = new RadioButton();
button.Name = btnName;
button.Width = 75;
button.Height = 40;
button.FontSize = 25;
button.Content = seachSiteID.Text;
SiteAddPanel.Children.Add(button);
seachSiteID.Text = "";
flyoutSiteID.Hide();
}
}
I have been trying to add MyButton_ContextRequested to each one of the dynamic buttons and haven't had much luck.
This is what the menu bar looks like:
MenuBar
I have a combobox to select the background color of a given application object. I'm filling the combobox with the code below, but I don't know how to retrieve the selected value to change the background color of the other object. Any help is most welcome. Thanks.
XAML
<ComboBox x:Name="cbxBackgroundColor" SelectionChanged="cbxBackgroundColor_SelectionChanged" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Fill="{Binding Name}" Width="32" Height="32" VerticalAlignment="Center" />
<TextBlock Text="{Binding Name}" Margin="10, 0, 0, 0" VerticalAlignment="Center" FontSize="12"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Code Behind
public VideoPage()
{
this.InitializeComponent();
cbxBackgroundColor.ItemsSource = typeof(Colors).GetProperties();
}
private void cbxBackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Code to set MyObject.Background with cbxBackgroundColor.SelectedItem
}
The following code works in wpf.
private void cbxBackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Color selectedColor = (Color)(cbxBackgroundColor.SelectedItem as PropertyInfo).GetValue(null, null);
this.Background = new SolidColorBrush(selectedColor);
or
MyObject.Background = new SolidColorBrush(selectedColor);
}
I'm new to WPF.
I have a ComboBox with multiple values and a HyperLink, whenever the ComboBox value changes, I want to change the NavigateUri of the HyperLink accordingly.
In the cs file, I have a dictionary, where the keys are the same as the combo items, and the value of each key is the link I want to navigate to according to the ComboBox selection.
LinkQuery["A"] = "https://google.com";
LinkQuery["B"] = "https://facebook.com";
LinkQuery["C"] = "https://Youtube.com";
<ComboBox x:Name="box_ComboBox" Visibility="Visible" Grid.Column="5" Grid.Row="4" Width="90"
ItemsSource="{Binding Path=Fields}"
IsSynchronizedWithCurrentItem="True"
SelectedValue="{Binding Path=Field}" Grid.ColumnSpan="2" HorizontalAlignment="Left" Height="22" VerticalAlignment="Top" SelectionChanged="component_ComboBox_SelectionChanged"/>
....
<TextBlock x:Name="LinkToQuery" Grid.Row="39" Grid.Column="1" Grid.ColumnSpan="4" Margin="10">
<Hyperlink x:Name="URLQuery" RequestNavigate="Hyperlink_RequestNavigate" Foreground="Blue">
Selected: A
</Hyperlink>
</TextBlock>
And the cs file:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(e.Uri.AbsoluteUri);
e.Handled = true;
}
private void component_ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
string selectedComponent = box_ComboBox.SelectedItem.ToString();
LinkToQuery.Text = string.Format("Selected: {0} ", box_ComboBox.SelectedItem.ToString());
URLQuery.NavigateUri = new System.Uri(LinkQuery[selectedComponent],System.UriKind.Absolute);
}
When I change the Combo selection, the text does change properly, but the link does not work.
Thank you.
Put a Run element inside the Hyperlink and set the Text property of this one:
<TextBlock x:Name="LinkToQuery" Grid.Row="39" Grid.Column="1" Grid.ColumnSpan="4" Margin="10">
<Hyperlink x:Name="URLQuery" RequestNavigate="Hyperlink_RequestNavigate" Foreground="Blue">
<Run x:Name="linkText" Text="Selected: A" />
</Hyperlink>
</TextBlock>
private void component_ComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
string selectedComponent = box_ComboBox.SelectedItem.ToString();
linkText.Text = string.Format("Selected: {0} ", selectedComponent);
URLQuery.NavigateUri = new System.Uri(LinkQuery[selectedComponent], System.UriKind.Absolute);
}
In this part of the code is the event TextChanged to enable the button in te applicationbar.
C#:
private void Textbox_TextChanged(object sender, EventArgs e)
{
ApplicationBarIconButton btn_guardar = ApplicationBar.Buttons[0] as applicationBarIconButton;
if (!string.IsNullOrEmpty(txt_nom_usuario.Text) && !string.IsNullOrEmpty(txt_edad_usuario.Text) && !string.IsNullOrEmpty(txt_peso_usuario.Text))
{
btn_guardar.IsEnabled = true;
}
else
btn_guardar.IsEnabled = false;
}
XAML:
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar Mode="Default" IsVisible="True">
<shell:ApplicationBarIconButton x:Name="btn_guardar" IconUri="/icons/appbar.save.rest.png" Text="Guardar" Click="btn_guardar_Click" IsEnabled="False" />
<shell:ApplicationBarIconButton x:Name="btn_atras" IconUri="/icons/appbar.back.rest.png" Text="AtrĂ¡s" Click="btn_atras_Click" />
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
<TextBlock x:Name="lbl_ingresanombre" Height="39" Margin="60,28,0,0" TextWrapping="Wrap" HorizontalAlignment="Left" VerticalAlignment="Top" Width="248" FontSize="29.333" FontFamily="{StaticResource Helvetica}"><Run Text="Ingresa "/><Run Text="tu nombre"/></TextBlock>
<TextBox x:Name="txt_nom_usuario" Height="63" Margin="47,58,69,0" TextWrapping="Wrap" Text="
" FontSize="21.333" VerticalAlignment="Top" IsEnabled="True" />
<TextBlock x:Name="lbl_edad" Height="38" Margin="60,117,0,0" TextWrapping="Wrap" Text="Ingresa tu edad" VerticalAlignment="Top" FontSize="29.333" HorizontalAlignment="Left" FontFamily="{StaticResource Helvetica}"/>
<TextBox x:Name="txt_edad_usuario" InputScope="TelephoneLocalNumber" Height="63" TextWrapping="Wrap" Text="
" FontSize="21.333" Margin="47,147,69,0" VerticalAlignment="Top" MaxLength="3" />
<TextBlock x:Name="lbl_peso" Height="42" Margin="60,0,0,178" TextWrapping="Wrap" Text="Peso" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="74" FontSize="29.333" d:LayoutOverrides="HorizontalAlignment" FontFamily="{StaticResource Helvetica}"/>
<TextBox x:Name="txt_peso_usuario" InputScope="TelephoneLocalNumber" Margin="47,0,69,125" TextWrapping="Wrap" Text="
" FontSize="21.333" Height="63" VerticalAlignment="Bottom"/>
The application bar doesn't support some basic features when it is set in XAML. You'll have to create the bar and buttons and/or menu items through code.
Here's an example how you can create the bar and add controls to it. The controls can then be accessed later from code:
//button
var appBarButton = new ApplicationBarIconButton
{
IconUri = new Uri("/Images/YourImage.png", UriKind.Relative),
Text = "click me"
};
appBarButton.Click += new EventHandler(appBarButton_Click);
//menu item
ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem
{
Text = "a menu item"
}
appBarMenuItem.Click += new EventHandler(appBarMenuItem_Click);
//application bar
//Note that this is not a variable declaration
//'ApplicationBar' is a property of 'PhoneApplicationPage'
ApplicationBar = new ApplicationBar();
ApplicationBar.Buttons.Add(appBarButton);
ApplicationBar.MenuItems.Add(appBarMenuItem);
//the events
private void appBarButton_Click(object sender, EventArgs e)
{
}
private void appBarMenuItem_Click(object sender, EventArgs e)
{
}
When all this is done, you've created your own ApplicationBar through code. Now you can change the properties from code, like this:
var theButton = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
if(someCondition)
{
theButton.IsEnabled = true;
}
else
{
theButton.IsEnabled = false;
}
//or shorter:
theButton.IsEnabled = someCondition
This is just an example. In the TextChanged events you can also access the ApplicationBar controls. In these events you can place above code to change the ApplicationBarButton. Hope this clears things up for you! More reading and info:
ApplicationBar Class
PhoneApplicationPage.ApplicationBar Property
How to change app bar icon buttons and menu items dynamically
I have a listbox showing name of place, building, x and y from a wcf service. How can I trigger a click from there and return the result to a map.
My Xaml
<ListBox x:Name="Results" Height="450" HorizontalAlignment="Center" VerticalAlignment="Bottom">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0 0 0 20">
<TextBlock Text="{Binding SearchVal}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeMediumLarge}" />
<TextBlock Text="{Binding Category}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeMedium}" />
<TextBlock Text="{Binding X}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeMedium}" />
<TextBlock Text="{Binding Y}" TextWrapping="Wrap" FontSize="{StaticResource PhoneFontSizeMedium}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
code behind my click action (Code from other sources)
public void searchResult_Click(object sender, RoutedEventArgs e)
{
//adds the map Point to the map when a results is selected.
var selectedSearchBtn = (Button)sender;
var selectedVal = (string)selectedSearchBtn.Content;
Classes.Global.searchedValue = selectedVal;
for (int i = 0; i < searchVal.Count; i++)
{
if (searchVal[i].Equals(selectedVal))
{
Classes.Global.posx = posx[i];
Classes.Global.posy = posy[i];
}
}
NavigationService.GoBack();
}
How can I use the above code to take the X and Y out ?
public void searchResult_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button; //Assuming your trigger is a button UI element.
if (button != null)
{
var place = button.DataContext as TestMap.Classes.Global.Place;
if (place != null)
{
Classes.Global.posx = place.posx;
Classes.Global.posy = place.posy;
}
}
NavigationService.GoBack();
}