Convert contents of a ListBoxItem to an instance of Thickness by using the ThicknessConverter

image_pdfimage_print


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="ThicknessConverter_Csharp.Window1"
    Title="ThicknessConverter Sample">
  <DockPanel Width="400" HorizontalAlignment="Left" VerticalAlignment="Top">
    <TextBlock DockPanel.Dock="Top" FontFamily="Verdana" FontSize="18" FontWeight="Bold" Margin="5">
      ThicknessConverter Sample</TextBlock>
    <Border Name="border1" Height="300" Width="300" Border.BorderThickness="2" Border.BorderBrush="Black" DockPanel.Dock="Top">
      <Grid Height="30" VerticalAlignment="Top">
        <Grid.RowDefinitions>
          <RowDefinition/>
          <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Name="bThickness"/>
        <TextBlock Grid.Row="1" Name="bColor"/>
      </Grid>
    </Border>
    <Grid DockPanel.Dock="Top">
      <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
      </Grid.RowDefinitions>
      <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
      </Grid.ColumnDefinitions>
      <TextBlock Grid.Row="1" Grid.Column="0" Margin="10,0,0,0" TextWrapping="Wrap">Change the BorderThickness Property:</TextBlock>
      <ListBox VerticalAlignment="Top" Grid.Column="1" Grid.Row="1" Width="50" Height="50" Margin="5" SelectionChanged="changeThickness">
        <ListBoxItem>0</ListBoxItem>
        <ListBoxItem>5</ListBoxItem>
        <ListBoxItem>10</ListBoxItem>
        <ListBoxItem>15</ListBoxItem>
        <ListBoxItem>20</ListBoxItem>
        <ListBoxItem>25</ListBoxItem>
        <ListBoxItem>30</ListBoxItem>
        <ListBoxItem>35</ListBoxItem>
        <ListBoxItem>40</ListBoxItem>
        <ListBoxItem>45</ListBoxItem>
        <ListBoxItem>50</ListBoxItem>
      </ListBox>
    </Grid>
  </DockPanel>        
</Window>

//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using System.Windows.Media;

namespace ThicknessConverter_Csharp
{
  public partial class Window1 : Window
  {
        public void changeThickness(object sender, SelectionChangedEventArgs args)
        {
      ListBoxItem li = ((sender as ListBox).SelectedItem as ListBoxItem);
      ThicknessConverter myThicknessConverter = new ThicknessConverter();
      Thickness th1 = (Thickness)myThicknessConverter.ConvertFromString(li.Content.ToString());
            border1.BorderThickness = th1;
            bThickness.Text = "Border.BorderThickness =" + li.Content.ToString();
        }
  }
}