wpf ritchbox
-
i try to change the size of text in ritchbox with code behind
TextRange tr = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
tr.ApplyPropertyValue(FontSizeProperty, (double)9);but i want to change
tr.ApplyPropertyValue(FontSizeProperty, (double)9)
by
double size=Convert.ToDouble(comboboxfontsize.selectedItem)// or selected value;
tr.ApplyPropertyValue(FontSizeProperty, size)i get an exception Impossible d'effectuer un cast d'un objet de type 'System.Windows.Controls.ComboBoxItem' en type 'System.IConvertible'. so how can i get the value selected item?
-
i try to change the size of text in ritchbox with code behind
TextRange tr = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
tr.ApplyPropertyValue(FontSizeProperty, (double)9);but i want to change
tr.ApplyPropertyValue(FontSizeProperty, (double)9)
by
double size=Convert.ToDouble(comboboxfontsize.selectedItem)// or selected value;
tr.ApplyPropertyValue(FontSizeProperty, size)i get an exception Impossible d'effectuer un cast d'un objet de type 'System.Windows.Controls.ComboBoxItem' en type 'System.IConvertible'. so how can i get the value selected item?
I don't know how you are populating the ComboBox, but I assume it is in the XAML. In this case the SelectedItem would be a ComboBoxItem which does not implement the
IConvertible
interface and so cannot be converted to a double. Personally, I would use WPF's binding mechanism to implement this using 2 properties, andObservableCollection
to hold the allowed font sizes, and an int property to hold the selected font size, something like this:-public ObservableCollection<int> Fonts
{
get
{
return new ObservableCollection<int>() { 8, 9, 10, 12, 14 };
}
}int selectedFontSize;
public int SelectedFontSize
{
get
{
return selectedFontSize;
}
set
{
if (selectedFontSize != value)
{
selectedFontSize = value;
OnPropertyChanged("SelectedFontSize");
}
}
}(this assumes you user control / window implements
INotifyPropertyChanged
). Then you can just create the bindings in your XAML like this:<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition />
</Grid.RowDefinitions>
<ComboBox ItemsSource="{Binding Fonts}" SelectedItem="{Binding SelectedFontSize}" Width="200" HorizontalAlignment="Left"/>
<RichTextBox Grid.Row="1">
<FlowDocument FontSize="{Binding SelectedFontSize}">
<Paragraph >
Hello World!
</Paragraph>
</FlowDocument>
</RichTextBox>
</Grid>and that is all there is to it, not forgetting to set the
DataContext
of your user control / window to itself like this in the constructor:public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}Hope this helps
When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman