코드 비하인드에서 프로그래밍 방식으로 DataTemplate을 만들려고합니다. textblocks의 텍스트 바인딩에있는 StringFormat이 작동하지 않는 것을 제외하면 모든 것이 완벽하게 작동합니다.바인딩의 WPF StringFormat이 코드 뒤에 작동하지 않습니다.
일반적으로 XAML에서, 나는과 같이이 작업을 수행 할 것입니다 :
<TextBlock Text={Binding MyProperty, StringFormat=0.0} />
그래서 난 그냥 내가 한 바인딩 개체의있는 StringFormat 속성을 설정할 수 있습니다 가정. 제대로 설정되었는지 확인 했는데도 내보기에는 여전히 형식이 반영되지 않습니다. 왜?
다음은 내 코드에서 발췌 한 것입니다. 나를 위해 동적으로 DataTemplate을 만드는 함수입니다. 문자 적으로 바인딩 경로를 ivalue 변환기와 모든 것으로 설정하는 것에서부터 모든 것이 완벽하게 작동합니다. 문자열 형식이 아닙니다. 당신이보고있는 것은 StringFormat
이 적용되고 있음을하지만, 문자열이 컨버터는 반환 값에 숫자 서식을하지 않는 것처럼
string propertyName = "myPropertyName";
FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
// the property I want is owned by myObject, which is a property of the datacontext
string bindingString = String.Format("myObject[{0}]", propertyName);
Binding binding = new Binding(bindingString)
{
Mode = BindingMode.OneWay,
Converter = (IValueConverter)Application.Current.FindResource("InvalidValuesConverter"),
StringFormat = "{0:F1}" // <-- Here is where I specify the stringFormat. I've also tried "0.0"
};
textBlock.SetBinding(TextBlock.TextProperty, binding);
[MCVE] (http://stackoverflow.com/help/mcve)는 가장 친한 친구입니다. 왜냐하면 지금은 모든 것이 [아마 맞을 것 같기 때문에] (http://stackoverflow.com/questions/14769529/binding-string-format-from-code-behind), 실제로 사용 된 유형 및 형식 문자열 및 거대한 파일이 없기 때문에 관련없는 코드의 경우 확신하기 어렵습니다. –
불필요한 코드를 제거하기 위해 편집 – user3685285
코드 숨김의 바인딩에는 변환기가 있으므로 StringFormat을 무시합니다. – Clemens