简体   繁体   中英

Add to label content instead of overwriting WPF C#

I have made a small WPF program. But it's my first and I've drawn a blank. I have figured out how to data-bind and add content from checkboxes to a label.

My issue is that when I press ex "Small coffee" and then afterwards press "with sugar" I want it to add to a string instead of writing over whatever was just there. I think I need to use Append. But it's my first and I've got no idea how to write it down in code. Thank you.

XAML

<RadioButton Content="Small" HorizontalAlignment="center" VerticalAlignment="Top" Margin="300,55,0,0" Click="SmlClicked"></RadioButton>
<RadioButton Content="Medium" HorizontalAlignment="center" VerticalAlignment="Top" Margin="450,55,0,0" Click="MdClicked"></RadioButton>

<CheckBox Name="SugarCheck" Content="Sugar" HorizontalAlignment="center" VerticalAlignment="Center" Margin="250,0,0,0" Checked="SugarChecked"></CheckBox>
<CheckBox Name="CreamCheck" Content="Cream" HorizontalAlignment="center" VerticalAlignment="Center" Margin="500,0,0,0" Checked="CreamChecked"></CheckBox>

<Label Name="order" Content="Your Coffee" HorizontalAlignment="center" VerticalAlignment="Center" Margin="170,145,0,0"></Label>

C#

private void SugarChecked(object sender, RoutedEventArgs e)
{
    order.Text+= "with sugar";
}

private void CreamChecked(object sender, RoutedEventArgs e)
{
    order.Content = "with cream";
}

private void SmlClicked(object sender, RoutedEventArgs e)
{
    order.Content = "Small";
}

private void MdClicked(object sender, RoutedEventArgs e)
{
    order.Content = "Medium";
}

private void LrgClicked(object sender, RoutedEventArgs e)
{
    order.Content = "Large";
}

You should just use the += operator as so:

private void SugarChecked(object sender, RoutedEventArgs e)
{
    order.Content += "with sugar";
}
private void CreamChecked(object sender, RoutedEventArgs e)
{
    order.Content += "with cream";
}

private void SmlClicked(object sender, RoutedEventArgs e)
{
    order.Content += "Small";
}

private void MdClicked(object sender, RoutedEventArgs e)
{
    order.Content += "Medium";
}

private void LrgClicked(object sender, RoutedEventArgs e)
{
    order.Content += "Large";
}

Though the format of your string will be awful...

The best would be to use this occasion to learn about Converters, have a Coffee class that changes according to what you do with your buttons, and bind it to your label using a custom converter :)

Check this link to learn about custom converters: https://www.wpf-tutorial.com/data-binding/value-conversion-with-ivalueconverter/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM