Label의 Content길이만큼 전체 Label의 Width를 변경하고 싶을 때. 쉬울 것 같지만 잠시 고민하게 되더군요. Converter를 사용해서 Content의 문자열 길이에 따라 Label의 Width가 변경되는 예제입니다.
✅ ContentWidthToWidthConverter
ContentWidthToWidthConverter.cs
public class ContentWidthToWidthConverter : IValueConverter
{
public object Convert(
object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(string))
{
return 8; // string이 아닐 때
}
string v = (string)value;
if (string.IsNullOrEmpty(v) == true)
{
return 8;
}
// (문자수 * 8) + 50(default offset)
return v.Length * 8 + 50;
}
public object ConvertBack(
object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
15번째 줄, return v.Length * 8 + 50; 의 숫자를 바꿔서 UI에 맞게 Width를 조절할 수 있습니다.
또는 parameter를 사용해서 Control 마다 Width의 변경폭을 바꿀 수도 있겠네요.
사용법
<UserControl.Resources>
<!-- Resources 에 등록 -->
<conv:ContentWidthToWidthConverter x:Key="widthConv"/>
</UserControl.Resources>
<Label Background="#3f3f3f"
Width="{Binding Content,
Converter={StaticResource widthConv},
RelativeSource={RelativeSource Self}}"
Foreground="#1f1f1f"/>
결과
Label의 문자열 길이에 따라 Label의 Width가 변경됩니다.
✅ ContentWidthToWidthConverter - 끝