0
我的WPF應用程序代碼在.cs文件中定義的函數調用上生成面板。在代碼中使用ItemControl來生成這些面板。我想通過它的按鈕來改變文本在選定面板中定義的文本框的文本對齊。查詢:我點擊按鈕並選擇面板文本框從左到右對齊從右到左,現在實現對齊設置是否選擇滑塊移動。這裏代碼是:如何通過INotify-Property在wpf中設置textbox.Text的對齊方式?
XAML FILE
<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));
}
}
}
}
對齊意味着Textbox.Text對齊left to right
或right to left
然後你將需要一個屬性對齊類型[FrameworkElement.FlowDirection](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.flowdirection.aspx)不是字符串,並且必須綁定到TextBox.FlowDirection。 – LPL
@LPL這將是'System.Windows.FlowDirection',並且是的,WPF能夠在DataBinding管道中隱式地將'string'轉換爲任何枚舉類型,因此您並不需要將您的VM綁定到'System。 Windows'爲了做到這一點 –
@HighCore我想,因爲我點擊按鈕它的內容從左到右或從右到左改變,這些改變應該適用於textbox.text – user2835256