Trying to have a default value for my radio buttons, but get flagged an NullReferenceException error.
private void rbImperial_Checked(object sender, RoutedEventArgs e)
{
txtInches.Visibility = Visibility.Visible;
lblInches.Visibility = Visibility.Visible;
lblWeight.Text = "lbs";
lblHeight.Text = "Feet";
}
private void rbMetric_Checked(object sender, RoutedEventArgs e)
{
lblHeight.Text = "cm";
txtInches.Visibility = Visibility.Collapsed;
lblInches.Visibility = Visibility.Collapsed;
lblWeight.Text = "kg";
}
rbImperial is the defaulted radio button that should be checked.
XAML:
<RadioButton x:Name="rbMetric" Content="Metric" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="132,244,0,0" Checked="rbMetric_Checked" ClickMode="Press"/>
<RadioButton x:Name="rbImperial" Content="Imperial" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="132,199,0,0" Checked="rbImperial_Checked" IsChecked="True" ClickMode="Press" />
If I don't have the rbImperial Checked property to be True to make it defaulted to be selected it runs perfectly fine.
What am I missing?
My issue when I try to run it.
Try setting the default value in the constructor. Not the prettiest method, but it should work. Alternatively, you can bind it to the ViewModel; that should work as well.
Related
I'm new to C# and XAML, so please excuse any obvious mistakes.
Let's say I wanted to create 100 checkboxes, all with the same layout, and when you click the checkbox, it makes the text in a label that's a child to that checkbox turn bold. I don't want to write out 100 functions for 100 checkboxes, I want to make a single function each checkbox can call that'll do the same thing.
<CheckBox VerticalContentAlignment="Center" Checked="CheckBox_Checked">
<WrapPanel>
<Image> Width="50" Source="Images/example.jpg"/>
<Label VerticalContentAlignment="Center">Extra cheese</Label>
</WrapPanel>
</CheckBox>
I'm able to get the WrapPanel nested under the CheckBox, but I can't seem to do the same to get the Label which is nested in the WrapPanel.
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox _cb = (CheckBox)sender;
WrapPanel _wp = (WrapPanel)(_cb).Content;
Label _lb = (Label)(_wp).Content;
_lb.FontWeight = FontWeights.Bold;
}
The wrap panel class doesn't have a content attribute. What you can use however is the Children attribute in a combination with FirstOrDefault OfType. the method could look somethind like this.
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
CheckBox _cb = (CheckBox)sender;
WrapPanel _wp = (WrapPanel)(_cb).Content;
Label lbl = _wp.Children.OfType<Label>().FirstOrDefault();
lbl.FontWeight = FontWeights.Bold;
}
You can easily access the element you want without the need for hierarchical transformations that exist in HTML and there is no need for different transformations, so we will have the following code:
File.xml
<CheckBox VerticalContentAlignment="Center" Checked="CheckBox_Checked" Unchecked="CheckBox_Checked">
<WrapPanel>
<Image Width="50" Source="Images/config.gif"/>
<Label VerticalContentAlignment="Center">Extra cheese</Label>
</WrapPanel>
</CheckBox>
File.cs
private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
if (sender is CheckBox _cb)
{
if (_cb.FontWeight == FontWeights.Normal)
_cb.FontWeight = FontWeights.Bold;
else
_cb.FontWeight = FontWeights.Normal;
}
}
I have a problem with change dynamically Visivility property of Listbox in wpf. After clicking button, property change but I have to double-click to refresh it. So after one click, nothing change. How can I do this?
<ListBox Visibility="Collapsed" Height="Auto" Width="Auto" HorizontalAlignment="Stretch" Name="listBox" VerticalAlignment="Stretch">
</ListBox>
private void btListBoxAction_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (listBox.Visibility == Visibility.Visible) {
listBox.Visibility = Visibility.Collapsed;
}
else {
listBox.Visibility = Visibility.Visible;
}
}
I have a little problem with saving some properties of my Buttons. The Buttons are small and with a variety of colors. When i press one button, some specified colors are changing... and i want to save them for the next start up. The textbox values i can save them but this ...i can't.
Code:
public MainWindow()
{
InitializeComponent();
//blueColor.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
//this.Property = Properties.Settings.Default.userColor;
}
private void blueColor_Click(object sender, RoutedEventArgs e)
{
var bc = new BrushConverter();
Main.Background = (Brush)bc.ConvertFrom("#FF007CE4");
startButton.Foreground = (Brush)bc.ConvertFrom("#FF007CE4");
closeButton.Foreground = (Brush)bc.ConvertFrom("#FF007CE4");
Properties.Settings.Default.userColor = true;
Properties.Settings.Default.Save();
}
private void purpleColor_Click(object sender, RoutedEventArgs e)
{
var bc = new BrushConverter();
Main.Background = (Brush)bc.ConvertFrom("#FF8701B9");
startButton.Foreground = (Brush)bc.ConvertFrom("#FF8701B9");
closeButton.Foreground = (Brush)bc.ConvertFrom("#FF8701B9");
}
I think I need the last clicked Button to be saved because I have allot of colors and maybe the .RaiseEvent can help here.
This is how it looks like:
Those 3 little buttons:
white
blue
red
are for changing the look of the program. At every start, the default is back.
You can store the color as a simple string and TypeConverter automatically converts it to type Brush. Below is an example.
Binding default value from XAML:
xmlns:properties="clr-namespace:WorkWithSettings.Properties"
<Button Width="100" Height="30"
Background="{Binding Source={x:Static properties:Settings.Default}, Path=Setting, Mode=TwoWay}" />
Set value from code:
private void Button_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.Setting = "#FF007CE4";
}
Note: Setting - this is just the type of String.
More information you can see here:
TypeConverters and XAML
Edit:
Below I'll show you an example, that I hope will help you.
So, go into the settings of the project: Project -> Properties -> Parameters. This opens a window of approximately:
Here we have a property ButtonColor, defined in the settings. For example, I took the Button, which changes the background, depending on the color of the pressed button.
In order to property Background the synchronize with settings to do, so:
<Button Width="100" Height="30"
Content="TestButton"
Background="{Binding Source={x:Static properties:Settings.Default}, Path=ButtonColor, Mode=TwoWay}" />
The default background color of white. Now, to set the background color at the button, we change the parameter settings, like this:
private void Blue_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "Blue";
}
To save changes to the settings, you need to call a method Save():
private void Save_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.Save();
}
Now, the next time you start the program, the color will be the one that was set last.
Full example
XAML
<Window x:Class="WorkWithSettings.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:properties="clr-namespace:WorkWithSettings.Properties"
WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Width="100" Height="30" Text="{Binding Source={x:Static properties:Settings.Default}, Path=ButtonColor, Mode=TwoWay}" Margin="0,60,0,0" />
<Button Width="100" Height="30" Content="TestButton" Background="{Binding Source={x:Static properties:Settings.Default}, Path=ButtonColor, Mode=TwoWay}" />
<WrapPanel>
<Button Name="Blue" Width="100" Height="30" Content="BlueColor" VerticalAlignment="Top" Click="Blue_Click" />
<Button Name="Red" Width="100" Height="30" Content="RedColor" VerticalAlignment="Top" Click="Red_Click" />
<Button Name="White" Width="100" Height="30" Content="WhiteColor" VerticalAlignment="Top" Click="White_Click" />
</WrapPanel>
<Button Name="Save" Width="60" Height="30" Content="Save" VerticalAlignment="Top" HorizontalAlignment="Right" Click="Save_Click" />
</Grid>
</Window>
Code behind
namespace WorkWithSettings
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void White_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "White";
}
private void Blue_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "Blue";
}
private void Red_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.ButtonColor = "Red";
}
private void Save_Click(object sender, RoutedEventArgs e)
{
WorkWithSettings.Properties.Settings.Default.Save();
}
}
}
Output
You probably need to create items in the Settings tab of your project that store the information about the color. I would recommend storing the hex strings. Then, on MainForm_Load retrieve those values.
Make sure to also put the settings in the User scope, or else they will reset each time they close the application.
I am developing a Windows 8 App using XAML and C#.
I have a problem with my ComboBox, and have a simple example to demonstrate it.
Add the following to a Layout Aware Page (New BasicPage)
<ComboBox x:Name="comboBox1" DropDownClosed="comboBox1_DropDownClosed" Visibility="Collapsed" HorizontalAlignment="Left" Margin="179,217,0,0" Grid.Row="1" VerticalAlignment="Top" Width="998" Height="51">
<x:String>Option 1</x:String>
<x:String>Option 2</x:String>
<x:String>Option 3</x:String>
</ComboBox>
<Button Click="Button_Click" Margin="585,130,0,416" Grid.Row="1" Height="82" Width="154">
<Viewbox>
<TextBlock Text="Press Me" />
</Viewbox>
</Button>
Add this to the page's CodeBehind
private void Button_Click(object sender, RoutedEventArgs e)
{
comboBox1.Visibility = Windows.UI.Xaml.Visibility.Visible;
comboBox1.IsDropDownOpen = true;
}
private void comboBox1_DropDownClosed(object sender, object e)
{
comboBox1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
Expected:
When the button is pressed, the ComboBox should appear and the options should expand, allowing the user to select one. Once the user has selected an option, the ComboBox disappears.
Actual Result:
When the button is pressed, nothing happens. If the button is pressed a second time, the ComboBox appears in a glitched state, and the app is essentially non-responsive. (All input is directed at the ComboBox, which never closes.
Note: The DropDownClosed event fires immediately after the Button_Click event does. Removing the event handler doesn't change anything, but it's interesting that the DropDownClosed event is firing.
Rejected Solution:
It was suggested to me to use Dispatcher.RunAsync to set IsDropDownOpen after the Visibility change has taken effect. This seems to be a race condition, because it only works some of the time. If there were a way to confirm that the ComboBox had been rendered visible, adding this check to the RunAsync method could solve the problem.
As a workaround, I'm currently delaying Dispatcher.RunAsync for 200 milliseconds, which is an annoying workaround. Any other ideas?
You're right, you need to make sure comboBox1 is actually rendered visible, before trying to set IsDropDownOpen. The way to do it is to make the second call via Dispatcher:
private void Button_Click(object sender, RoutedEventArgs e)
{
comboBox1.Visibility = Windows.UI.Xaml.Visibility.Visible;
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => comboBox1.IsDropDownOpen = true);
}
What a nasty bug, ah?
A simple workaround is instead of using the Visibility property, use Opacity. It works as expected:
<ComboBox x:Name="comboBox1" DropDownClosed="comboBox1_DropDownClosed" Opacity="0" HorizontalAlignment="Left" Margin="179,217,0,0" Grid.Row="1" VerticalAlignment="Top" Width="998" Height="51">
<x:String>Option 1</x:String>
<x:String>Option 2</x:String>
<x:String>Option 3</x:String>
</ComboBox>
private void Button_Click(object sender, RoutedEventArgs e) {
comboBox1.Opacity = 1;
comboBox1.IsDropDownOpen = true;
}
private void comboBox1_DropDownClosed(object sender, object e) {
comboBox1.Opacity = 0;
}
Cheers!
I've tested the following on my desktop and Surface device, and it seems to work all the time. It is a variation on delaying setting IsDropDownOpen. I understand you may have tried some variation of this that produced a race condition. I am not seeing a race condtion, so hopefully it works for you as well.
// need this for Task
using System.Threading.Tasks;
...
// note async keyword added to function signature
async private void Button_Click(object sender, RoutedEventArgs e)
{
comboBox1.Visibility = Windows.UI.Xaml.Visibility.Visible;
// add small delay before opening dropdown
await Task.Delay(1);
comboBox1.IsDropDownOpen = true;
}
I have a webbrowser that uses a simple forward and backward navigation scheme, and may also refresh or stop navigation if the user so choses. All navigation is working correctly, but my issue arises when I try to toggle the 'refresh' and 'stop' buttons depending on whether the webbrowser is Navigating or has Navigated. I would like for the refresh button to be set to visible as long as no navigation is occuring, and for the stop button to be set to visible while navigation is occuring. My basic implementation is as follows but I cannot seem to get the buttons to toggle from Visible to Collapsed depending on these scenarios.
MainPage.xaml
<Button x:Name="RefreshButton" Content="" Style="{StaticResource RefreshBtn}" Grid.Column="0" Grid.Row="0" Visibility="Visible" Click="RefreshButton_Click" toolkit:TiltEffect.IsTiltEnabled="True">
<Button x:Name="StopButton" Content="" Style="{StaticResource StopBtn}" Grid.Column="0" Grid.Row="0" Visibility="Collapsed" Click="StopButton_Click" toolkit:TiltEffect.IsTiltEnabled="True"/>
MainPage.xaml.cs
public MainPage()
{
InitializeComponent();
//Change Navigation buttons if the browser is currently Navigating
if (TheBrowser._IsNavigating == false)
{
RefreshButton.Visibility = Visibility.Visible;
StopButton.Visibility = Visibility.Collapsed;
}
else
{
RefreshButton.Visibility = Visibility.Collapsed;
StopButton.Visibility = Visibility.Visible;
}
//while (TheBrowser._IsNavigating == true)
//{
// RefreshButton.Visibility = Visibility.Collapsed;
// StopButton.Visibility = Visibility.Visible;
//}
}
WebBrowser.xaml.cs
//Flag to check if the browser is navigating
public bool _IsNavigating = false;
void TheWebBrowser_Navigating(object sender,
Microsoft.Phone.Controls.NavigatingEventArgs e)
{
_IsNavigating = true;
}
void TheWebBrowser_Navigated(object sender,
System.Windows.Navigation.NavigationEventArgs e)
{
_IsNavigating = false;
}
My WebBrowser.xaml.cs is a webbrowser user control which is embedded into MainPage.xaml and named TheBrowser. When debugging, I can see the changes in the bool variable _IsNavigating between true and false as shown above but this change is not detected in MainPage.xaml.cs which is why I think the button visibility does not change. Any help with this issue would be greatly appreciated.. I have run out of ideas of how to fix this! Thanks in advance.
The code for setting the visibility is in the wrong place, right now it is only called upon page construction.
You have to call the code whenever your _isNavigating variable changes.
Do the following:
void ChangeVisibility()
{
if (TheBrowser._IsNavigating == false)
{
RefreshButton.Visibility = Visibility.Visible;
StopButton.Visibility = Visibility.Collapsed;
}
else
{
RefreshButton.Visibility = Visibility.Collapsed;
StopButton.Visibility = Visibility.Visible;
}
}
void TheWebBrowser_Navigating(object sender,
Microsoft.Phone.Controls.NavigatingEventArgs e)
{
_IsNavigating = true;
ChangeVisibility();
}
void TheWebBrowser_Navigated(object sender,
System.Windows.Navigation.NavigationEventArgs e)
{
_IsNavigating = false;
ChangeVisibility();
}