如何设置文本框的对齐方式.wpf 中的文本通过 INotify-Property
本文关键字:文本 INotify-Property wpf 对齐 置文本 方式 | 更新日期: 2023-09-27 18:34:02
我的 WPF 应用程序代码在文件中定义的函数调用.cs生成面板。代码中使用了 ItemControl 来生成这些面板。我想通过其按钮更改所选面板中定义的文本框的文本对齐方式。查询:我单击按钮并将选择面板文本框的对齐方式从左到右和从右到左更改,现在如果选择滑块移动,则实现对齐设置。这里的代码是:
XAML 文件
<ItemsControl x:Name="lstItemsClassM">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Button Content="{Binding Alignment, Mode=TwoWay}"
Click="Button_Click"
Tag="{Binding PKId}" />
<TextBox x:Name="txtText"
Width="300"
Height="100"
Text="{Binding Text, Mode=TwoWay}"
FontSize="{Binding FontSize, Mode=OneWay}"
TextAlignment="{Binding Alignment, Mode=OneWay}" />
<Slider Minimum="10"
Maximum="30"
Value="{Binding FontSize, Mode=TwoWay}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
.CS文件
protected ObservableCollection<ClassM> texts = new ObservableCollection<ClassM>();
int dv;
public Window2()
{
InitializeComponent();
dv=1;
texts.Add(new ClassM() { PKId=dv, Text = "Test 1" });
dv=2;
texts.Add(new ClassM() { PKId=dv, Text = "Test 2" });
lstItemsClassM.ItemsSource = texts;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var myValue = ((Button)sender).Tag;
foreach (var f in texts.ToList())
{
if (f.PKId.ToString() == myValue.ToString())
{
f._alignment = "Right";
MessageBox.Show(f._alignment);
}
}
}
}
public class ClassM : INotifyPropertyChanged
{
private string _id;
private int _pkid;
private string _text;
private double _fontSize = 10;
public string _alignment="Left";
public int PKId
{
get { return _pkid; }
set
{
if (value != _pkid)
{
_pkid = value;
NotifyPropertyChanged();
}
}
}
public string Id
{
get { return _id; }
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged();
}
}
}
public string Text
{
get { return _text; }
set
{
if (value != _text)
{
_text = value;
NotifyPropertyChanged();
}
}
}
public double FontSize
{
get { return _fontSize; }
set
{
if (value != _fontSize)
{
_fontSize = value;
NotifyPropertyChanged();
}
}
}
public string Alignment
{
get { return _alignment; }
set
{
if (value != _alignment)
{
_alignment = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
对齐方式表示文本框。文本对齐方式left to right
或right to left
最好的解决方案是使用富文本框来对齐文本。如果你愿意,我可以找一个实现来读取文字字符串和格式。