Right-Click on Dynamically created RadioButtons - c#

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

Related

send data from one window to another c# xaml wpf

i want to send Data from one Textbox on window One to a label on window Two.
starting with window two:
<StackPanel>
<StackPanel x:Name="ButtonStackPanel" Height="Auto" Width="Auto">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical">
<Button Style="{DynamicResource ButtonStyle}" Content="To The Dark Side" Click="OnClickToDarkSide"/>
<Button Style="{DynamicResource ButtonStyle}" Content="To The Gray" Click="OnClickToGraySide"/>
<Button Style="{DynamicResource ButtonStyle}" Content="To The Light Side" Click="OnClickToLightSide"/>
</StackPanel>
<Border HorizontalAlignment="Center" VerticalAlignment="Stretch" Background="Red" Height="Auto" Width="2"/>
<Label Style="{DynamicResource LabelStyle}" x:Name="theTextBlock" Content="{Binding Source=CodeText}"/>
<Border HorizontalAlignment="Center" VerticalAlignment="Stretch" Background="Red" Height="Auto" Width="2"/>
<ToggleButton Style="{DynamicResource ToggleButtonStyle}" Content="Open Style Window" Name="StyleWindowButton" Click="OnClickOpenStyleWindow"/>
<ToggleButton Style="{DynamicResource ToggleButtonStyle}" Content="Open Text Window" Name="TextWindowButton" Click="OnClickOpenTextWindow"/>
</StackPanel>
<Border Height="2" Width="Auto" Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
</StackPanel>
<Border Height="2" Width="Auto" Background="Red" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
</StackPanel>
Codebehind of Window Two:
public MainWindow()
{
(App.Current as App).CodeText = _jediCode;
InitializeComponent();
}
private void OnClickToDarkSide(object sender, RoutedEventArgs e)
{
(App.Current as App).ChangeSkin(Skin.Dark);
(App.Current as App).CodeText = _sithCode;
theTextBlock.Content = (App.Current as App).CodeText;
}
private void OnClickToLightSide(object sender, RoutedEventArgs e)
{
(App.Current as App).ChangeSkin(Skin.Light);
(App.Current as App).CodeText = _jediCode;
theTextBlock.Content = (App.Current as App).CodeText;
}
private void OnClickToGraySide(object sender, RoutedEventArgs e)
{
(App.Current as App).ChangeSkin(Skin.Gray);
(App.Current as App).CodeText = _grayCode;
theTextBlock.Content = (App.Current as App).CodeText;
}
private void OnClickOpenStyleWindow(object sender, RoutedEventArgs e)
{
if (StyleWindowButton.IsChecked == true)
{
styleWindow = new StyleWindow();
styleWindow.Show();
}
else
{
styleWindow.Close();
styleWindow = null;
}
}
private void OnClickOpenTextWindow(object sender, RoutedEventArgs e)
{
if (TextWindowButton.IsChecked == true)
{
textWindow = new InputWindow();
textWindow.Show();
}
else
{
textWindow.Close();
textWindow = null;
}
}
}
window one:
<Grid>
<TextBox HorizontalAlignment="Left" VerticalAlignment="Top" Height="200" Width="200" TextWrapping="Wrap"
AcceptsReturn="True" AcceptsTab="True" Text="{Binding Path=CodeText, Source={x:Static Application.Current}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Margin="10,10,0,0">
<!-- TODO: trigger change from this textbox to the textblock in mainwindow -->
</TextBox>
</Grid>
code behind of one is empty.
app.xaml.cs:
public string CodeText
{
get => _codeText;
set { _codeText = value; OnPropertyChanged(nameof(CodeText)); }
}
Ok, the current behavior is clicking on one of the buttons (Dark Side, Gray, Light Side) leads to changes in the CodeText Property, which leads to a change of the content of the label of Window Two and the text of TextBox of Window One. Changing the text of the TextBox, changes also the CodeText Property, but does not lead to a change in the label and thats confusing, why does it work the one way, but not the other.
hope you have a hint for me. :) Maybe i missed a trigger or a kind of refresh for the label
bindings in window One and Two are set differently. (window Two does it wrong, Content="{Binding Source=CodeText}" is not valid binding)
in fact, window Two removes the binding by assigning CodeText directly as local value:
theTextBlock.Content = (App.Current as App).CodeText;
you should remove that line, and use the same binding as in window One:
<Label Style="{DynamicResource LabelStyle}" x:Name="theTextBlock"
Content="{Binding Path=CodeText, Source={x:Static Application.Current}}"/>

Creating a few controls in code behind failing

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);
}

Get button content in event

I have the code in XAML:
<Button Grid.Column="0" Grid.Row="1" x:Name="btnSete" Click="btn_Click">
<ContentControl.Content>
<Viewbox Margin="3">
<TextBlock Text="7"/>
</Viewbox>
</ContentControl.Content>
</Button>
And code behind:
private void btn_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)e.Source;
txbDisplay.Text = btn.Content.ToString();
}
how do I get the value of <TextBlock Text="7"/> in btn_Click?
Based on your XAML, btn.Content should be the instance of the Viewbox. Then the Child property of the Viewbox should be your TextBlock.
So you should be able to do this (inside your button click event handler):
var viewBox = (Viewbox)btn.Content;
var textBlock = (TextBlock)viewBox.Child;
var text = textBlock.Text; // This is the value you were looking for
txbDisplay.Text = text;
Also, just as a helpful note, the <ContentControl.Content> ... </ContentControl.Content> part of your XAML is superfluous. That block could just be written as:
<Button Grid.Column="0" Grid.Row="1" x:Name="btnSete" Click="btn_Click">
<Viewbox Margin="3">
<TextBlock Text="7"/>
</Viewbox>
</Button>
See the "XAML Content Properties" section on this page for more information why that is if you're not sure.

Hyperlinks in TextBlock in windows phone 8.0 using C#

how to generate hyperlink from text writeen in textbox to textblock in windows phone 8.0 using C#
ex:- i entered
www.google.com in textbox and clicked on button after button click
the result should be
www.google.com
with hyperlink in textblock
You can easily put Hyperlink into RichTextBlock (in WP8.1 Runtime). I've also put Run in hyperlink so it's easier to manage its content. Example:
<StackPanel>
<TextBox Name="myTextBox" Width="200"/>
<RichTextBlock TextWrapping="Wrap" VerticalAlignment="Center" TextAlignment="Center">
<Paragraph>
<Run Text="This is a link to google:"/>
<LineBreak/>
<Hyperlink x:Name="myhyperlink" Click="myhyperlink_Click">
<Run x:Name="hyperText" Text="textInside"/>
</Hyperlink>
<LineBreak/>
<Run Text="you can click it to invoke doEvent in your code."/>
</Paragraph>
</RichTextBlock>
</StackPanel>
In the code behind - some logic example:
public MainPage()
{
this.InitializeComponent();
myTextBox.TextChanged += (sender, e) => hyperText.Text = myTextBox.Text;
}
private async void myhyperlink_Click(Windows.UI.Xaml.Documents.Hyperlink sender, Windows.UI.Xaml.Documents.HyperlinkClickEventArgs args)
{
await Windows.System.Launcher.LaunchUriAsync(new Uri(#"http://" + myTextBox.Text));
}
Note that in WP8.0 and WP8.1 Silverlight you will have to use RichTextBox with IsReadOnly = true
Use a HyperlinkButton control.
<HyperlinkButton NavigateUri="http://www.google.com">
<HyperlinkButton.Content>
<TextBlock Text="google.com" />
</HyperlinkButton.Content>
</HyperlinkButton>
try this:
XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="0">
<StackPanel x:Name="stack">
<TextBox x:Name="txtInput"></TextBox>
<Button Content="Create Link" Click="Button_Click"/>
</StackPanel>
</Grid>
CS:
private void Button_Click(object sender, RoutedEventArgs e)
{
if (txtInput.Text != "")
{
HyperlinkButton obj = new HyperlinkButton();
obj.NavigateUri = new Uri(txtInput.Text,UriKind.RelativeOrAbsolute);
obj.Content = txtInput.Text;
obj.TargetName = "_blank";
this.stack.Children.Add(obj);
}
}
for e.g. try with http://google.com in textbox
Try this
xaml
<StackPanel x:Name="stack">
<TextBlock Text="{Binding LineThree}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBox x:Name="txtInput"></TextBox>
<Button Content="Create Link" Click="Button_Click"/>
<RichTextBox x:Name="textBox" ></RichTextBox>
</StackPanel>
and the button click in the cs file
private void Button_Click(object sender, RoutedEventArgs e)
{
Hyperlink hyperlink = new Hyperlink();
hyperlink.Inlines.Add(txtInput.Text);
Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add(hyperlink);
textBox.Blocks.Add(myParagraph);
}

Disable/Enable applicationbar Button in runtime with event textchanged (Windows Phone)

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

Categories

Resources