WPF에서 더미 디자인 타임 데이터에 사용할 수있는 접근 방식은 무엇입니까?
식 혼합없이 작업하고 있으며 vs2010에서 XAML 편집기를 사용하고 있습니다. 이것의 지혜는 제쳐두고 디자인 타임 데이터 바인딩에 대한 필요성이 점점 더 커지고 있습니다. 간단한 경우에는 FallbackValue
속성이 매우 잘 작동합니다 (Textboxes 및 TextBlocks 등). 그러나 특히 등을 다룰 때 ItemsControl
, 실행 파일을 실행하지 않고도 컨트롤과 데이터 템플릿을 조정하고 조정할 수 있도록 디자이너에서 볼 수있는 샘플 데이터가 실제로 필요합니다.
ObjectDataProvider
유형에 바인딩 할 수 있으므로 시각화를위한 디자인 타임 데이터를 제공 할 수 있다는 것을 알고 있지만 디자인 타임을로드하여 리소스를 낭비하지 않고 실제 런타임 데이터를 바인딩 할 수 있도록 약간의 저글링이 있습니다. 더미 데이터 및 런타임 바인딩.
내가 원하는 것은 "John", "Paul", "George"및 "Ringo"가 내에서 스타일 가능한 항목으로 XAML 디자이너에 ItemsControl
표시되지만 응용 프로그램이 표시 될 때 실제 데이터가 표시되도록하는 기능입니다. 실행합니다.
또한 Blend는 런타임 조건에서 WPF가 효과적으로 무시하는 디자인 타임 바인딩 데이터를 정의하는 멋진 특성을 허용한다는 것을 알고 있습니다.
그래서 내 질문은 다음과 같습니다.
1. Visual Studio XAML 디자이너에서 컬렉션 및 중요하지 않은 데이터의 디자인 타임 바인딩을 활용 한 다음 런타임 바인딩으로 원활하게 전환하려면 어떻게해야합니까?
2. 다른 사람들은이 디자인 타임 대 런타임 데이터 문제를 어떻게 해결 했습니까? 제 경우에는 둘 다에 대해 동일한 데이터를 매우 쉽게 사용할 수 없습니다 (예를 들어 데이터베이스 쿼리로 할 수있는 것처럼).
3. 데이터 통합 XAML 디자인에 사용할 수있는 식 혼합의 대안이 있습니까? (몇 가지 대안이 있다는 것을 알고 있지만 특별히 사용할 수 있고 바인딩 된 샘플 데이터 등을 볼 수있는 것을 원합니까?)
VS2010을 사용하면 디자인 타임 속성을 사용할 수 있습니다 (SL 및 WPF 모두에서 작동). 어쨌든 나는 보통 모의 데이터 소스를 가지고 있으므로 다음과 같은 문제입니다.
네임 스페이스 선언 추가
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
창 / 제어 리소스에 모의 데이터 컨텍스트 추가
<UserControl.Resources> <ViewModels:MockXViewModel x:Key="DesignViewModel"/> </UserControl.Resources>
디자인 타임 데이터 컨텍스트 설정
<Grid d:DataContext="{Binding Source={StaticResource DesignViewModel}}" ...
충분히 잘 작동합니다.
Goran의 받아 들여진 답변과 Rene의 훌륭한 의견이 합쳐져 있습니다.
네임 스페이스 선언을 추가하십시오.
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
코드에서 디자인 타임 데이터 컨텍스트를 참조하십시오.
<Grid d:DataContext="{d:DesignInstance Type=ViewModels:MockXViewModel, IsDesignTimeCreatable=True}" ...
Karl Shifflett는 VS2008 및 VS2010에서 똑같이 잘 작동해야하는 접근 방식을 설명합니다.
WPF 및 Silverlight 프로젝트의 Visual Studio 2008 Cider Designer에서 디자인 타임 데이터보기
Laurent Bugnion은 Expression Blend에 중점을 둔 유사한 접근 방식을 사용합니다. 그것은 수 VS2010 작동,하지만 난 아직 확인하지 않았습니다.
Microsoft Expression Blend의 디자인 모드에서 데이터 시뮬레이션
Visual Studio 2010 및 Expression Blend 4의 새로운 디자인 타임 기능이 옵션이 될 수 있습니다.
작동 방식은 WPF WAF (Application Framework) 의 BookLibrary 샘플 애플리케이션에 나와 있습니다. .NET4 버전을 다운로드하십시오.
.NET 4.5 및 Visual Studio 2013에서 디자인 타임 데이터를 생성하는 데이 접근 방식을 사용합니다.
ViewModel이 하나뿐입니다. 뷰 모델에는 IsInDesignMode
디자인 모드가 활성화되었는지 여부를 알려주 는 속성 이 있습니다 (class 참조 ViewModelBase
). 그런 다음 뷰 모델 생성자에서 디자인 타임 데이터 (항목 컨트롤 채우기와 같은)를 설정할 수 있습니다.
게다가 뷰 모델 생성자에서 실제 데이터를로드하지 않을 것입니다. 이로 인해 런타임에 문제가 발생할 수 있지만 디자인 타임에 데이터를 설정하는 것은 문제가되지 않습니다.
public abstract class ViewModelBase
{
public bool IsInDesignMode
{
get
{
return DesignerProperties.GetIsInDesignMode(new DependencyObject());
}
}
}
public class ExampleViewModel : ViewModelBase
{
public ExampleViewModel()
{
if (IsInDesignMode == true)
{
LoadDesignTimeData();
}
}
private void LoadDesignTimeData()
{
// Load design time data here
}
}
Using Visual Studio 2017 I have been trying to follow all of the guides and questions such as this and I was still facing a <ItemsControl>
which simply did not execute the code I had inside the constructor of a DesignFooViewModel
which inherits from FooViewModel
. I confirmed the "did not execute" part following this "handy" MSDN guide (spoiler: MessageBox
debugging). While this is not directly related to the original question, I hope it will save others a lot of time.
Turns out I was doing nothing wrong. The issue was that my application needs to be built for x64. As the Visual Studio is still in 2018 a 32-bit process and apparently cannot spin a 64-bit host process for the designer part it cannot use my x64 classes. The really bad thing is that there are no errors to be found in any log I could think of.
So if you stumble upon this question because you are seeing bogus data in with your design time view model (for example: <TextBlock Text="{Binding Name}"/>
shows up Name
no matter you set the property to) the cause is likely to be your x64 build. If you are unable to change your build configuration to anycpu or x86 because of dependencies, consider creating a new project which is fully anycpu and does not have the dependencies (or any dependencies). So you end up splitting most or all but the initialization parts of the code away from your "WPF App" project into a "C# class library" project.
For the codebase I am working on I think this will force healthy separation of concerns at the cost of some code duplication which is probably net positive thing.
Similar to the top rated answer, but better in my opinion: You can create a static property to return an instance of design data and reference it directly from XAML like so:
<d:UserControl.DataContext>
<Binding Source="{x:Static designTimeNamespace:DesignTimeViewModels.MyViewModel}" />
</d:UserControl.DataContext>
This avoids the need to use UserControl.Resources
. Your static property can function as a factory allowing you to construct non-trivial data types - for example if you do not have a default ctor, you can call a factory or container here to inject in appropriate dependencies.
'program tip' 카테고리의 다른 글
파이썬의 다양한 문자열 형식화 방법 — 오래된 것 (예정)은 더 이상 사용되지 않습니까? (0) | 2020.08.27 |
---|---|
GNU / Linux에서 SVN (Subversion) 서버를 설정하는 방법-Ubuntu (0) | 2020.08.27 |
C ++에 파일이 있는지 확인하는 가장 좋은 방법은 무엇입니까? (0) | 2020.08.26 |
C #에서 배열을 비교하는 방법은 무엇입니까? (0) | 2020.08.26 |
Linux의 Bash에서 한 번에 여러 파일을 삭제하는 방법은 무엇입니까? (0) | 2020.08.26 |