余白

https://blog.lacolaco.net/ に移転しました

ListViewで選択状態の時有効になるボタン

ListViewで選択状態のアイテムが有るときだけ押せるボタン。出来てしまえば簡単だけど時間がかかったので忘れないようにメモ。
Livet使ってます。ここでは特に関係ないですが。

XAML

<ListView x:Name="listview" ItemsSource="{Binding Path=Items}" 
                      IsSynchronizedWithCurrentItem="True">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"/>
       </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
             
<Button Content="ボタン" Command="{Binding Command, Mode=OneWay}">
    <Button.IsEnabled>
        <Binding ElementName="listview" Path="SelectedItem" Mode="OneWay" Converter="{StaticResource NullToBooleanConverter}"/>
    </Button.IsEnabled>
</Button>

ButtonのIsEnabledにlistviewのSelectedItemをバインドしています。
nullでなければTrue というふうになるようにConverterを用意しました

public class NullToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return false;
            PropertyInfo propertyInfo = value.GetType().GetProperty("Count");
            if (propertyInfo != null)
            {
                int count = (int)propertyInfo.GetValue(value, null);
                return count > 0;
            }
            if (!(value is bool || value is bool?)) return true;
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }

CSでコードを一切書かずにできました。