Студопедия

Главная страница Случайная страница

Разделы сайта

АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника






Создание заготовки решения






  • Создайте решение WpfApp с проектом WpfText1 и назначьте его стартовым


Добавьте к проекту новый файл с именем FontPropertyLists.cs


Текстовый элемент Label

  • Заполните файл FontPropertyLists.cs следующим кодом
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Media; namespace WpfText1{ /// < summary> /// Код класса из примера MSDN /// < /summary> public class FontPropertyLists { static Collection< FontFamily> fontFaces; static Collection< FontStyle> fontStyles; static Collection< FontWeight> fontWeights; static Collection< double> fontSizes; static int maxFontSizes = 36; /// < summary> /// Заполняет коллекцию доступных системе FontFamily /// < /summary> public static ICollection< FontFamily> FontFaces { get { if (fontFaces == null) fontFaces = new Collection< FontFamily> (); foreach (FontFamily fontFamily in Fonts.SystemFontFamilies) { fontFaces.Add(fontFamily); } return fontFaces; } } /// < summary> /// Заполняет коллекцию доступных FontStyles /// < /summary> public static ICollection FontStyles { get { if (fontStyles == null) { fontStyles = new Collection< FontStyle> (); fontStyles.Add(System.Windows.FontStyles.Normal); fontStyles.Add(System.Windows.FontStyles.Oblique); fontStyles.Add(System.Windows.FontStyles.Italic); } return fontStyles; } } /// < summary> /// Заполняет коллекцию доступных FontWeight /// < /summary> public static ICollection FontWeights { get { if (fontWeights == null) { fontWeights = new Collection< FontWeight> (); Unique(System.Windows.FontWeights.Thin); Unique(System.Windows.FontWeights.Light); Unique(System.Windows.FontWeights.Regular); Unique(System.Windows.FontWeights.Normal); Unique(System.Windows.FontWeights.Medium); Unique(System.Windows.FontWeights.Heavy); Unique(System.Windows.FontWeights.SemiBold); Unique(System.Windows.FontWeights.DemiBold); Unique(System.Windows.FontWeights.Bold); Unique(System.Windows.FontWeights.Black); Unique(System.Windows.FontWeights.ExtraLight); Unique(System.Windows.FontWeights.ExtraBold); Unique(System.Windows.FontWeights.ExtraBlack); Unique(System.Windows.FontWeights.UltraLight); Unique(System.Windows.FontWeights.UltraBold); Unique(System.Windows.FontWeights.UltraBlack); } return fontWeights; } } static void Unique(FontWeight fontWeight) { if (fontWeights.IndexOf(fontWeight) == -1) fontWeights.Add(fontWeight); } /// < summary> /// Заполняет коллекцию доступных FontSizes /// < /summary> public static Collection< double> FontSizes { get { if (fontSizes == null) { fontSizes = new Collection< double> (); for (double i = 8; i < = maxFontSizes; i++) fontSizes.Add(i); } return fontSizes; } } // Методы для преобразования из TypeName в Type public static bool CanParseFontStyle(string fontStyleName) { try { FontStyleConverter converter = new FontStyleConverter(); converter.ConvertFromString(fontStyleName); return true; } catch { return false; } } public static FontStyle ParseFontStyle(string fontStyleName) { FontStyleConverter converter = new FontStyleConverter(); return (FontStyle)converter.ConvertFromString(fontStyleName); } public static bool CanParseFontWeight(string fontWeightName) { try { FontWeightConverter converter = new FontWeightConverter(); converter.ConvertFromString(fontWeightName); return true; } catch { return false; } } public static FontWeight ParseFontWeight(string fontWeightName) { FontWeightConverter converter = new FontWeightConverter(); return (FontWeight)converter.ConvertFromString(fontWeightName); } }}
  • Заполните файл Window1.xaml следующей разметкой
< Window x: Class=" WpfText1.Window1" xmlns=" https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x=" https://schemas.microsoft.com/winfx/2006/xaml" Title=" Window1" Background=" LightGray" Height=" 300" Width=" 300" MinHeight=" 300" MinWidth=" 300" ResizeMode=" CanResizeWithGrip" WindowStartupLocation=" CenterScreen" FocusManager.FocusedElement=" {Binding ElementName='fontSizeListBox'}" > < TabControl> <! --Вкладка Label--> < TabItem Header=" Label" > <! --Сетка 4x3--> < Grid> < Grid.RowDefinitions> < RowDefinition Height=" 60" /> < RowDefinition Height=" Auto" /> < RowDefinition Height=" Auto" /> < RowDefinition Height=" *" /> < /Grid.RowDefinitions> < Grid.ColumnDefinitions> <! --Пропорции ширины столбцов--> < ColumnDefinition Width=" 2.7*" /> < ColumnDefinition Width=" 1.3*" /> < ColumnDefinition Width=" 1*" /> < /Grid.ColumnDefinitions> < Border Grid.Row=" 0" Grid.ColumnSpan=" 3" BorderThickness=" 3" BorderBrush=" Violet" > < Label VerticalContentAlignment=" Center" HorizontalContentAlignment=" Center" Foreground=" Red" FontWeight=" {Binding ElementName=fontWeightListBox, Path=SelectedItem}" FontSize=" {Binding ElementName=fontSizeListBox, Path=SelectedItem}" FontFamily=" {Binding ElementName=fontFamilyListBox, Path=SelectedItem}" Content=" Элемент Label" /> < /Border> < Label Grid.Row=" 1" Grid.Column=" 0" HorizontalContentAlignment=" Center" Content=" FontFamily: " /> < TextBox Grid.Row=" 2" Grid.Column=" 0" Name=" fontFamilyTextBox" Text=" {Binding ElementName=fontFamilyListBox, Path=SelectedItem}" TextChanged=" fontFamilyTextBox_TextChanged" /> < ListBox Grid.Row=" 3" Grid.Column=" 0" Name=" fontFamilyListBox" SelectedIndex=" 0" /> < Label Grid.Row=" 1" Grid.Column=" 1" HorizontalContentAlignment=" Center" Content=" FontWeight: " /> < TextBox Grid.Row=" 2" Grid.Column=" 1" Name=" fontWeightTextBox" Text=" {Binding ElementName=fontWeightListBox, Path=SelectedItem}" TextChanged=" fontWeightTextBox_TextChanged" /> < ListBox Grid.Row=" 3" Grid.Column=" 1" Name=" fontWeightListBox" SelectedIndex=" 0" /> < Label Grid.Row=" 1" Grid.Column=" 2" HorizontalContentAlignment=" Center" Content=" FontSize: " /> < TextBox Grid.Row=" 2" Grid.Column=" 2" Name=" fontSizeTextBox" Text=" {Binding ElementName=fontSizeListBox, Path=SelectedItem}" TextChanged=" fontSizeTextBox_TextChanged" /> < ListBox Grid.Row=" 3" Grid.Column=" 2" Name=" fontSizeListBox" SelectedIndex=" 0" /> < /Grid> < /TabItem> < /TabControl> < /Window>
  • Зарегистрированные в элементах TextBox обработчики событий TextChanged заполните в файле Window1.xaml.cs
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfText1{ public partial class Window1: Window { public Window1() { InitializeComponent(); // Заполняем коллекции и подключаем их к спискам ListBox this.fontFamilyListBox.ItemsSource = FontPropertyLists.FontFaces; this.fontWeightListBox.ItemsSource = FontPropertyLists.FontWeights; this.fontSizeListBox.ItemsSource = FontPropertyLists.FontSizes; // Выполняется после XAML this.fontSizeListBox.SelectedIndex = this.fontSizeListBox.Items.Count - 1; this.fontSizeListBox.ScrollIntoView(this.fontSizeListBox.Items.Count - 1); } // Сокрытие унаследованных от Window одноименных свойств new public FontFamily FontFamily { get { return (FontFamily)this.fontFamilyListBox.SelectedItem; } set { this.fontFamilyListBox.SelectedItem = value; // Выделить this.fontFamilyListBox.ScrollIntoView(value); // Прокрутить до видимого } } new public FontWeight FontWeight { get { return (FontWeight)this.fontWeightListBox.SelectedItem; } set { this.fontWeightListBox.SelectedItem = value; // Выделить this.fontWeightListBox.ScrollIntoView(value); // Прокрутить до видимого } } new public double FontSize { get { return (double)this.fontSizeListBox.SelectedItem; } set { this.fontSizeListBox.SelectedItem = value; // Выделить this.fontSizeListBox.ScrollIntoView(value); // Прокрутить до видимого } } private void fontFamilyTextBox_TextChanged(object sender, TextChangedEventArgs e) { // Привести ListBox в соответствие с содержимым TextBox this.FontFamily = new FontFamily(this.fontFamilyTextBox.Text); } private void fontWeightTextBox_TextChanged(object sender, TextChangedEventArgs e) { // Привести ListBox в соответствие с содержимым TextBox if (FontPropertyLists.CanParseFontWeight(this.fontWeightTextBox.Text)) { this.FontWeight = FontPropertyLists.ParseFontWeight(this.fontWeightTextBox.Text); } } private void fontSizeTextBox_TextChanged(object sender, TextChangedEventArgs e) { // Привести ListBox в соответствие с содержимым TextBox double fontSize; if (double.TryParse(this.fontSizeTextBox.Text, out fontSize)) { this.FontSize = fontSize; // В поле действительно число } } }}
  • Запустите проект - получим инструмент для просмотра основных атрибутов библиотечного текстового элемента Label

 

  • Обратите внимание, как компоновка окна сохраняется при изменении его размеров и что окно имеет минимальный размер. Разберитесь с кодом разметки и процедурным кодом C#





© 2023 :: MyLektsii.ru :: Мои Лекции
Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав.
Копирование текстов разрешено только с указанием индексируемой ссылки на источник.