问题
I'm stumbling on this data converter stuff, especially with relation to multiple rows and dynamically show/hide an image.
Lets take a master/detail data perspective. On a given view (presentation), I have header information and a data grid showing a bunch of line items. Before saving the line items, there could be one or more rows having missing/invalid data. I want to display a graphic image to the left of the line item giving the user some visual cue that ...hey, this row needs to be fixed...
So, I have a datatable on my ViewModel that has an extra column indicating if there are errors associated with the row as boolean as datatable column types have no idea how to handle the wpf "visibility" data type. This datatable.DefaultView is the actual basis of displaying the data (which works). I'm just stuck on this final getting the image to dynamically show/hide properly.
I've read about converters, and have a class that does nothing but act as the converter. So, I can only suggest the following for those who can offer help.
My ViewModel has a property exposing the DefaultView
public DataView MyDetailView
{ get { return MyTable.DefaultView; }}
For simplicity, this table has two columns..
RecordIsInvalid (boolean),
LineItem (int)
回答1:
Using BooleanToVisibilityConverter Binding should be pretty straightforward:
<Image Visibility="{Binding RecordIsInvalid,
Converter={StaticResource BooleanToVisibilityConverter}}" ... />
But as far as I understand you have a single RecordIsInvalid
flag and LineNumber
which refer to a specific Row. What actually bound to each Row? Do you have someting like ItemViewModel which correspond to each row? Basically each Item should be in charge to validate it's own state and expose IsValid
property in this way things would be much clean and easy so you would be able simply bound to IsValid
in scope of each grid view Item.
EDIT: Answer to comment
You should not instantiate and expose converter yourself.
- Put a converter class in some adequate namespace like
MyProject.GUI.Converters
- In View.xaml add namespace alias for Converetrs, see *1
- Add converter into the Control/Window resources within XAML, see *2
*1: MyView.xaml
<UserControl ...
xmlns:Converters="clr-namespace:MyProject.GUI.Converters" />
*2: MyView.xaml
<UserControl.Resources>
<Converters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</UserControl.Resources>
来源:https://stackoverflow.com/questions/8050816/using-converter-with-image-within-datagrid