할 수 없는 이유를 바인딩 크기의 양식을 ApplicationSettings?
-
09-06-2019 - |
문제
업데이트:해결 코드
나는 그것을 가지고 작업을 참조하십시오 나의 답변을 아래를 위해 코드...
원래의 게시물
로 Tundey 에서 지적 그의 대답이 나 마지막 질문, 결합할 수 있습니다 거의 모든 것에 대한 윈도우 폼 제어하 ApplicationSettings 꽤 자연스럽게.그래서 정말 방법을 이렇게 형태로 크기는? 이 튜토리얼 말를 처리해야 합 크기를 명시적으로 저장할 수 있도록 RestoreBounds 신의 크기는 경우 창을 최대화하거나 최소화됩니다.그러나 내가 기대가 사용할 수 있습니 같은 속성:
public Size RestoreSize
{
get
{
if (this.WindowState == FormWindowState.Normal)
{
return this.Size;
}
else
{
return this.RestoreBounds.Size;
}
}
set
{
...
}
}
하지만 아무것도 보이지 않았는 방법에 바인딩하이에서 디자이너(크기 는 특히 누락에서 PropertyBinding 목록).
해결책
마지막으로 와서 양식에 하위 클래스에서는 이 문제를 해결합,한번에 모두.를 사용:
- 에서 상속 RestorableForm 대의 형태입니다.
- 추가 바인딩(ApplicationSettings)->(PropertyBinding)을 WindowRestoreState.
- 전화 속성입니다.설정합니다.기본입니다.저장()면 창을 닫습니다.
이제는 창의 위치와 상태로 기억될 것이 사 세션이 있습니다.다음과 같은 제안에서 다른 포스터는 아래 나는 포함 기능 ConstrainToScreen 는 확인 창에 적합에 사용할 수 있을 때 표시됩 복 자체입니다.
코드
// Consider this code public domain. If you want, you can even tell
// your boss, attractive women, or the other guy in your cube that
// you wrote it. Enjoy!
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace Utilities
{
public class RestorableForm : Form, INotifyPropertyChanged
{
// We invoke this event when the binding needs to be updated.
public event PropertyChangedEventHandler PropertyChanged;
// This stores the last window position and state
private WindowRestoreStateInfo windowRestoreState;
// Now we define the property that we will bind to our settings.
[Browsable(false)] // Don't show it in the Properties list
[SettingsBindable(true)] // But do enable binding to settings
public WindowRestoreStateInfo WindowRestoreState
{
get { return windowRestoreState; }
set
{
windowRestoreState = value;
if (PropertyChanged != null)
{
// If anybody's listening, let them know the
// binding needs to be updated:
PropertyChanged(this,
new PropertyChangedEventArgs("WindowRestoreState"));
}
}
}
protected override void OnClosing(CancelEventArgs e)
{
WindowRestoreState = new WindowRestoreStateInfo();
WindowRestoreState.Bounds
= WindowState == FormWindowState.Normal ?
Bounds : RestoreBounds;
WindowRestoreState.WindowState = WindowState;
base.OnClosing(e);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (WindowRestoreState != null)
{
Bounds = ConstrainToScreen(WindowRestoreState.Bounds);
WindowState = WindowRestoreState.WindowState;
}
}
// This helper class stores both position and state.
// That way, we only have to set one binding.
public class WindowRestoreStateInfo
{
Rectangle bounds;
public Rectangle Bounds
{
get { return bounds; }
set { bounds = value; }
}
FormWindowState windowState;
public FormWindowState WindowState
{
get { return windowState; }
set { windowState = value; }
}
}
private Rectangle ConstrainToScreen(Rectangle bounds)
{
Screen screen = Screen.FromRectangle(WindowRestoreState.Bounds);
Rectangle workingArea = screen.WorkingArea;
int width = Math.Min(bounds.Width, workingArea.Width);
int height = Math.Min(bounds.Height, workingArea.Height);
// mmm....minimax
int left = Math.Min(workingArea.Right - width,
Math.Max(bounds.Left, workingArea.Left));
int top = Math.Min(workingArea.Bottom - height,
Math.Max(bounds.Top, workingArea.Top));
return new Rectangle(left, top, width, height);
}
}
}
설정을 바 참조
다른 팁
는 이유 형태입니다.크기 속에서 사용할 수 없는 설정을 바인딩 UI 때문에 이 숙박 시설 표시 DesignerSerializationVisibility.숨겨진.즉,디자이너는 방법을 알고하지 않을 serialise 그것은 혼자 생성에 대한 데이터 바인딩니다.대신 형태입니다.ClientSize 숙박 시설은 하나를 얻전.
만약 당신이 시도하고 영리한 바인딩하여 위치 고 ClientSize, 당신이 볼 수 또 다른 문제가 발생할 수 있습니다.크기를 조정할 때 당신의 형태에서 왼쪽 또는 위쪽 가장자리에,당신은 참 이상한 행동을 했다.이것은 분명하는 방법과 관련된 두 방법으로 데이터 바인딩 작품의 컨텍스트에서 속성을 세트는 상호간에 서로 영향을 미칩니다.모두 위치 고 ClientSize 결국 통화로서 일반적으로 사용되는 방법 SetBoundsCore().
또한,데이터 바인딩하는 속도 위치 고 크기 은 효율적이지 않습니다.사용자는 움직이거나 크기를 형성,Windows 보내는 메시지의 수백 양식의 원인,데이터 바인딩 할 논리를 많이 처리할 때,모든 당신이 정말로 원하는 저장소 지난 위치 및 크기하기 전에 양식을 닫습니다.
이것은 매우 간단한 버전의 내가 무엇을 할:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.MyState = this.WindowState;
if (this.WindowState == FormWindowState.Normal)
{
Properties.Settings.Default.MySize = this.Size;
Properties.Settings.Default.MyLoc = this.Location;
}
else
{
Properties.Settings.Default.MySize = this.RestoreBounds.Size;
Properties.Settings.Default.MyLoc = this.RestoreBounds.Location;
}
Properties.Settings.Default.Save();
}
private void MyForm_Load(object sender, EventArgs e)
{
this.Size = Properties.Settings.Default.MySize;
this.Location = Properties.Settings.Default.MyLoc;
this.WindowState = Properties.Settings.Default.MyState;
}
왜 이것은 아주 단순화 버전입니까?기 때문에 이렇게 제가 많은 난이도 보이는 것보다:-)
잘 나는 빠른 재생이고 당신은 올바른 방법은 없지만을 직접 bind 의 크기는 양 AppSettings 추가할 수 있습니다 자신의 가치와 크기 변경 load.
나는 것이 좋을 것이 일반적인 기능입니다,당신은 서브 클래스 형태로 만들고 그것이 자동으로 문니다.Config 에 대한 형태로 크기를 설정합니다.
(또는 롤 자신의 파일이..그것을 얻을 쿼리 Xml 파일로"formname.settings.xml"나는 뭔가?-thinking out loud!)..
Heres 무엇을 했다(매우 거친,오류 검사 etc.).
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="FormHeight" value="500" />
<add key ="FormWidth" value="200"/>
</appSettings>
</configuration>
양식 코드
private void Form1_Load(object sender, EventArgs e)
{
string height = ConfigurationManager.AppSettings["FormHeight"];
int h = int.Parse(height);
string width = ConfigurationManager.AppSettings["FormWidth"];
int w = int.Parse(width);
this.Size = new Size(h, w);
}
중 하나 이상 크기 바인딩은 허용되지 않기 때문에 스크린 사이에 변경될 수 있습니다.
선적 크기 때 다시 해상도 줄 수 있는 결과를 제목 표시줄에는 한계를 넘어의 화면.
당신이 또한 필요 조심하 모니터링 여러 설정,어디 모니터링을 더 이상 사용하지 못할 수 있습할 때 다음 응용 프로그램이 실행됩니다.
동의함으로 Rob Cooper 의 대답이다.그러나 내가 생각하는 마틴은 매우 좋은 지점입니다.처럼 아무것도 없는 사용자를 열 응용 프로그램과 응용 프로그램은 화면에!
그래서 현실에서,당신은 모두를 결합한 답변과 마음에 부담 현재 화면의 치수 설정하기 전에 너의 양식의 크기입니다.