How to set different HorizontalAlignment to ListBoxItems

前端 未结 5 1141
情歌与酒
情歌与酒 2021-01-21 12:12

I posted a question yesterday but I think I failed to explain it correctly.

Let me try again.

So this is my goal:

5条回答
  •  Happy的楠姐
    2021-01-21 12:39

    Instead of using Grid, use DockPanel with HorizontalAlignment="Stretch" instead.

    As for the data alignment, assuming you are using ItemsSource, then there is some workaround.

    First, the easy thing to do is to add HorizontalAlignment WPF property to your message class. The message class will determine whether the HorizontalAlignment will be left or right. However this will make dependency more higher with the UI.

    The code will be like this:

    
    

    Second, the better (or clean) way to do is to do HorizontalAlignment binding with converter (IValueConverter). It is harder and you must define your own converter, but your code will be tidier. Then your message has an enum of Income or Outcome message, named MessageType. Then in your converter define it like:

    public object Convert(object value, Type targetType, 
      object parameter, CultureInfo culture)
    {
      if(parameter is MessageType){
        if(((MessageType)parameter) == MessageType.Income){
          return HorizontalAlignment.Left;
        }
        else{
          return HorizontalAlignment.Right;
        }
      }
    }
    

    The code above is not tested, so please consider error. For the implementation of Converter, please search it in some places. I still cannot generate Converter binding without help source :)

提交回复
热议问题