문제
들어오는 바운드 정수에 일정한 값을 추가하고 싶습니다. 사실 나는 동일한 소스 값에 결합하고 싶지만 다른 상수를 추가하는 여러 장소가 있습니다. 따라서 이상적인 솔루션은 다음과 같은 것입니다 ...
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/>
(참고 : 이것은 아이디어를 보여주는 예입니다. 내 실제 바인딩 시나리오는 텍스트 상자의 캔버스 속성이 아닙니다. 그러나 이것은 아이디어를 더 명확하게 보여줍니다)
현재 내가 생각할 수있는 유일한 해결책은 각각 동일한 내부 값과 다른 상수를 추가하는 많은 다른 소스 속성을 노출시키는 것입니다. 그래서 나는 이런 일을 할 수 있습니다 ...
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/>
<TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/>
그러나 이것은 미래에 새로운 상수에 대한 새로운 특성을 계속 추가해야 할 수도 있기 때문에 이것은 꽤 어둡습니다. 또한 추가 값을 변경 해야하는 경우 꽤 naff 인 소스 객체를 변경해야합니다.
이것보다 더 일반적인 방법이 있어야합니까? WPF 전문가는 아이디어가 있습니까?
다른 팁
나는 a를 사용한다 MathConverter
모든 간단한 산술 작업을 수행하기 위해 만들었습니다. 변환기의 코드는 다음과 같습니다 여기 그리고 다음과 같이 사용할 수 있습니다.
<TextBox Canvas.Top="{Binding SomeValue,
Converter={StaticResource MathConverter},
ConverterParameter=@VALUE+5}" />
더 고급 산술 작업과 함께 사용할 수도 있습니다.
Width="{Binding ElementName=RootWindow, Path=ActualWidth,
Converter={StaticResource MathConverter},
ConverterParameter=((@VALUE-200)*.3)}"
값 변환기를 사용하는 것은 UI에 바인딩 될 때 소스 값을 수정할 수 있으므로 문제에 대한 좋은 솔루션입니다.
나는 두 곳에서 다음을 사용했습니다.
public class AddValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
object result = value;
int parameterValue;
if (value != null && targetType == typeof(Int32) &&
int.TryParse((string)parameter,
NumberStyles.Integer, culture, out parameterValue))
{
result = (int)value + (int)parameterValue;
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
예시
<Setter Property="Grid.ColumnSpan"
Value="{Binding
Path=ColumnDefinitions.Count,
RelativeSource={RelativeSource AncestorType=Grid},
Converter={StaticResource addValueConverter},
ConverterParameter=1}"
/>
나는 WPF를 사용한 적이 없지만 가능한 솔루션이 있습니다.
바인딩 경로가 맵에 맵을지도 할 수 있습니까? 그렇다면 인수 (키)를 취할 수 있어야합니다. 맵 인터페이스를 구현하는 클래스를 만들어야하지만 실제로 키에 추가 된 "맵"을 초기화 한 기본 값을 반환합니다.
public Integer get( Integer key ) { return baseInt + key; } // or some such
태그에서 숫자를 전달할 수있는 능력이 없으면 원래 값에서 다른 델타를 반환하는 방법을 알 수 없습니다.