I have some problem in wpf application.
In XAML:
<Expander Header="SomeHeader" Style="{StaticResource ExpanderStyle}" IsExpanded="{Binding ElementName=Errors, Converter={StaticResource visibilityConverter}, Path=IsExpanded}" >
<RichTextBox ScrollViewer.VerticalScrollBarVisibility="Visible" Style="{StaticResource RichTextBoxStyle}" Foreground="Red" IsReadOnly="True">
<FlowDocument>
<Paragraph>
<ItemsControl ItemsSource="{Binding Path=Errors}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Style="{StaticResource ErrorTextBlockStyle}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Paragraph>
</FlowDocument>
</RichTextBox>
</Expander>
In my ViewModelClass:
private List<string> errors;
public List<string> Errors
{
get { return errors; }
set
{
errors = value;
OnPropertyChanged("Errors");
}
}
在构造函数中:
public MainWindowViewModel()
{
if (IsInDesignMode) return;
Errors = new List<string>();
}
在测试方法中:
private void TestExcute()
{
Errors = "Some error";
}
在这种情况下,错误消息不会显示在wpf窗口中 . 但是,如果我将构造函数中的代码更改为next:
public MainWindowViewModel()
{
if (IsInDesignMode) return;
Errors = new List<string>{"errorMessage1", "errorMessage2"};
}
显示:
errorMessage1
errorMessage2
是什么原因 ?
我有新问题 . 在这个wpf应用程序中,我也使用了Expander控件 . 如何创建自动展开,然后Errors.count> 0?
我创建转换器:
public class VisibilityConverter:IValueConverter {public object Convert(object value,Type targetType,object parameter,System.Globalization.CultureInfo culture){LoadFile loadFile =(LoadFile)value;
if (loadingFile.ExcelErrors.Count > 0)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
LoadFile是一个声明了Errors属性的类 .
1 回答
我认为你在
TestExcute
中犯了一个错误,而你写的问题是不是要写Errors.Add("some error")
?如果是这样,那么你的
ItemsControl
不会对变化做出反应,因为属性没有变化Errors
- 没有调用setter .将您的
List<string>
更改为ObservableCollection<string>
此类通知其内容已更改,UI将对此作出反应 .